访问PHP中受保护的变量


Accessing protected variables in PHP

我试图访问从父类扩展的第二个子类中的受保护变量,但每次我试图访问它们时,它们都是NULL。

对我来说奇怪的是,我可以毫无问题地访问父类的受保护函数(例如:第二个子班的$this->_submit。)我检查了父类和变量设置在那里,所以我确信我遗漏了一些愚蠢的东西(仍在学习OOP)。也许和构造函数有关?但是如果我在第二个子进程中调用parent::__construct(),它会抛出一个错误,因为缺少config的细节?

父母

<?php defined('SYSPATH') or die('No direct script access.');
abstract class Rimage {
    protected $_config;
    protected $_service;
    protected $_client;
public static function instance($config, $service)
{
    return new Rimage_Client($config, $service);
}
public function __construct($config = array(), $service = NULL)
{
    $this->_config  = $config;
    $this->_service = $service;
    $this->_client = new SoapClient('url');
}
}
?>

第一个孩子
<?php defined('SYSPATH') or die('No direct script access.');
class Rimage_Client extends Rimage {
    protected $_caller;
    public function __construct($config = array(), $service = NULL)
    {
        parent::__construct($config, $service);
        $this->_caller = Arr::get($config, 'caller', array());
    }
    public function get($id = NULL)
    {   
    return new Rimage_Job_Status($id);
    }
    protected function _submit($options, $request_class)
    {
        $job->request = $options;
        $response = $this->_client->$request_class($job); /** Client is undefined??**/
        return $response;   
    }
} // End Rimage_Client
?>

第二个孩子

<?php defined('SYSPATH') or die('No direct script access.');
class Rimage_Job_Status extends Rimage_Client {
    public function __construct($id) 
    {       
        return $this->_retrieve($id);
    }
    private function _retrieve($id = NULL)
    {
        $options->CallerId  = $this->_caller; /** $_caller is undefined??? **/
        $options->JobId     = $id;
        $response = $this->_submit($options, 'test');
        return $response->whatever;
    }
} // End Rimage_Job_Status
?>

Rimage::instance($config,'job')->get('12345');

调用代码

编辑:

我得到的错误是$_client在子中为NULL,但不在父中…$_caller在第二个子节点中为NULL。

干杯,圣诞快乐!

__construct()函数不被继承到子类,因此没有理由在第二个子类中设置$this->_caller。要执行父类的__construct函数,需要在子类的__构造函数中调用parent::__construct()

构造new Rimage_Job_Status时,执行Rimage_Job_Status::__construct函数。它所做的唯一事情就是调用Rimage_Job_Status::_retrieve()。在Rimage_Job_Status::_retrieve中,您尝试访问$this->_caller。但这是不存在的,因为在我刚才描述的步骤中没有设置它。

老实说,这是一个相当混乱的方式来使用对象和类。我建议您完全重写/重新考虑您在这里要做的事情。