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);