4

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

?>
fusion3k
  • 11,568
  • 4
  • 25
  • 47
Bivek
  • 1,380
  • 10
  • 24
  • 3
    No, it can't access the private property in the parent class (doesn't even know that it exists), so it creates a new public property in the extended class – Mark Baker Apr 07 '16 at 09:59
  • just do the `var_dump` of `$object` i think you will have the answer – Chetan Ameta Apr 07 '16 at 10:06

1 Answers1

2

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!

ST2OD
  • 705
  • 1
  • 5
  • 15
  • _Thats what the access modifier `protected` is for._ - ... you mean `private`? typo? – Federkun Apr 07 '16 at 11:24
  • 1
    @Federico no, with `protected` the subclass has access to the variable. With `private` the subclass doesn't have access. _"That's what the access modifier `protected` is for"._ – ST2OD Apr 07 '16 at 11:46