Why is PHP private variables working on extended class?

不打扰是莪最后的温柔 提交于 2021-02-02 09:26:21

问题


Shouldn't it generate error when i try to set the value of a property from the extended class instead of a base class?

<?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:


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:

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!



来源:https://stackoverflow.com/questions/36472579/why-is-php-private-variables-working-on-extended-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!