php中一个成员权限迷惑

WBOY
Release: 2016-06-13 11:56:35
Original
1004 people have browsed it

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 {
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 {
private $a;
public function __construct() {
$this->arr = array(
'a' => '1',
);
parent::__construct();
}
public function __set($name, $val) {
$this->$name = $val;
}
}

$obj = new Son();
print_r($obj);
Copy after login
Son Object
(
[a:Son:private] => 1
[arr:protected] => Array
(
[a] => 1
)

)

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!