为什么PHP私有变量在扩展类上工作?

时间:2016-04-07 09:52:29

标签: php constructor private access-specifier

当我尝试从扩展类而不是基类设置属性的值时,它不应该生成错误吗?

<?php
class first{
    public $id = 22;
    private $name;
    protected $email;
    public function __construct(){
        echo "Base function constructor<br />";
    }
    public function printit(){
        echo "Hello World<br />";
    }
    public function __destruct(){
        echo "Base function destructor!<br />";
    }
}
class second extends first{
    public function __construct($myName, $myEmail){
        $this->name = $myName;
        $this->email = $myEmail;
        $this->reveal();
    }
    public function reveal(){
        echo $this->name.'<br />';
        echo $this->email.'<br />';
    }
}
$object = new second('sth','aaa@bbb.com');

?>

1 个答案:

答案 0 :(得分:1)

Private variables are not accessible in subclasses. Thats what the access modifier protected is for. What happened here is that when you access a variable that doesn't exist, it creates one for you with the default access modifier of public.

Here is the UML to show you the state:

enter image description here

Please note: the subclass still has access to all the public and protected methods and variables from its superclass - but are not in the UML diagram!