Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

constructor - 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','[email protected]');

?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...