Search code examples
phpconstructorprivateaccess-specifier

Why is PHP private variables working on extended class?


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

?>

Solution

  • 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!