The permissions of a member in php are confusing: & lt ;? Phpclass & nbsp; Far {& nbsp; protected & nbsp; $ arr; & nbsp; protected & nbsp; function & nbsp; init () & nbsp; {& nbsp; the permission of a member in php is confusing.
Problem: The following code is available:
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 $;
Public function _ construct (){
$ This-> arr = array (
'A' => '1 ',
);
Parent: :__ construct ();
}
}
$ Obj = new Son ();
Print_r ($ obj );
Q: Why is a null instead of 1 in the output result of $ obj.
Son Object
(
[A: protected] => 1
[Arr: protected] => Array
(
[A] => 1
)
)
Question 2: If you change the private $ a of the subclass to protected $ a or public $ a in the above code, the output is:
Son Object
(
[A: protected] => 1
[Arr: protected] => Array
(
[A] => 1
)
[Bb] => 1
)
Why?
------ Solution --------------------
Your _ set method is defined in Far, so he cannot access Son's private attributes.
You can write it in this way.
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);Son Object
(
[A: Son: private] => 1
[Arr: protected] => Array
(
[A] => 1
)
)