【发布时间】:2020-01-02 06:58:59
【问题描述】:
我在 Codeigniter 中实现驱动程序时遇到问题。
我需要访问父类的方法作为子类中的全局变量。
这是我的代码
父类
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Prueba extends CI_Driver_Library {
protected $notifica_grupo;
public function __construct() {
$this->valid_drivers = array('uno', 'dos');
$this->notifica_grupo = "foo";
}
public function notifica_grupo() {
return $this->notifica_grupo;
}
}
儿童班
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Prueba_uno extends CI_Driver {
private $ci;
protected $notifica;
public function __construct() {
$this->ci =& get_instance();
$this->notifica = $this->_parent->notifica_grupo();
}
public function test1(){
echo $this->notifica;
}
}
调用$this->prueba->uno->test1()时出现以下错误;
Type: Error
Message: Call to a member function notifica_grupo() on null
Filename: /xxx/application/libraries/Prueba/drivers/Prueba_uno.php
Line Number: 10
Backtrace:
File: /xxx/application/controllers/Test.php
Line: 33
Function: __get
所以,我的问题是......有没有办法从孩子的构造访问父方法?
更新: 我尝试了不同的想法,没有一个奏效。这些是场景:
- 试图直接获取变量而不是从父方法获取:
$this->notifica = $this->_parent->notifica_grupo;。结果:
Message: Trying to get property 'notifica_grupo' of non-object
- 在 Child 类中将“扩展 CI_Driver”更改为“扩展 Prueba”。结果:
Invalid driver requested: Prueba_uno__parent
- 在 Child 类中将“extends CI_Driver”更改为“extends Prueba”,并在子构造函数中将变量值中的“_parent”删除为:
$this->notifica = $this->notifica_grupo();返回此错误:
Message: Call to undefined method Prueba_uno::decorate()
- 在子构造函数中添加
parent::__construct();,然后尝试从父方法或直接变量中获取值。返回:
Type: Error
Message: Cannot call constructor
【问题讨论】:
-
你应该写
class Prueba_uno extends Prueba而不是class Prueba_uno extends CI_Driver -
嗨@L.Faros 我试过了,但它仍然不起作用。我已经更新了我的问题以显示不同情况下的不同错误。顺便说一句,我使用 CodeIgniter 而不是纯 PHP。
标签: php codeigniter driver