Home  >  Article  >  Backend Development  >  php中一个成员权限迷惑

php中一个成员权限迷惑

WBOY
WBOYOriginal
2016-06-13 11:56:351056browse

php中一个成员权限困惑
问题:有如下代码:
class Far
{
    protected $arr;

    protected function init() {
        foreach ($this->arr as $k => $val) {
            $this->$k = $val;
        }
    }

    public function __construct() {
        $this->init();
    }

    public function __set($name, $val) {
        $this->$name = $val;
    }
}

class Son extends Far
{
    protected $a;

    public function __construct() {
        $this->arr = array(
            'a' => '1',
        );

        parent::__construct();
    }
}

$obj = new Son();
print_r($obj);
问:为什么$obj输出的结果中,a不是1,而是null.
Son Object
(
    [a:protected] => 1
    [arr:protected] => Array
        (
            [a] => 1
        )

)

问题2:如果把上述代码中,子类的private $a 改成protected $a 或public $a,则输出:
Son Object
(
    [a:protected] => 1
    [arr:protected] => Array
        (
            [a] => 1
        )

    [bb] => 1
)

为什么?
------解决方案--------------------
你的 __set 方法是定义在 Far 中的,所以他不能访问 Son 的私有属性
这样写就可以了

class Far {<br />    protected $arr;<br />    protected function init() {<br />        foreach ($this->arr as $k => $val) {<br />            $this->$k = $val;<br />        }<br />    }<br /><br />    public function __construct() {<br />        $this->init();<br />    }<br /><br />    public function __set($name, $val) {<br />        $this->$name = $val;<br />    }<br />}<br /><br />class Son extends Far {<br />    private $a;<br />    public function __construct() {<br />        $this->arr = array(<br />            'a' => '1',<br />        );<br />        parent::__construct();<br />    }<br />    public function __set($name, $val) {<br />        $this->$name = $val;<br />    }<br />}<br /><br />$obj = new Son();<br />print_r($obj);
Son Object
(
    [a:Son:private] => 1
    [arr:protected] => Array
        (
            [a] => 1
        )

)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn