Confused about permissions of a member in php

Source: Internet
Author: User
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
)

)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.