how to access parent variable from child class

2019-09-02 19:34发布

i have two classes one parent and the other extends , I need to use main vars in extended class. for example

class parentClass
{
    $this->value = null
    function __construct()
    {
        echo "im parent" ;
    }

}
class childClass extends parentClass
{

    function sayIt()
    {
        var_dump($this->value);
    }
}

$p = new parentClass ; 
$p->value = 500 ; 

$c = new childClass ; 
$c->sayIt(); // this output null ! i want it to output 500 , how i can do that

thanks

标签: php oop class
3条回答
地球回转人心会变
2楼-- · 2019-09-02 19:35

that's not the way inheritance works. The childClass is not automatically connected to the parent class, it just inherits from the parentClass it just inherits all public and protected variables/methods from teh parent. It is not connected to the parent's instances.

if you wnat it to output 500 you have to assign it to the child class instance somehow:

$c = new childClass ; 
$c->value = 500;
$c->sayIt()

If you need a variable shared between all classes and instances you can use a static variable.

查看更多
Viruses.
3楼-- · 2019-09-02 19:49

you are confusing with class constructs and references.

$p is an instance of the parentclass.

$c is an instance of the childclass.

they don't share their data.

查看更多
放荡不羁爱自由
4楼-- · 2019-09-02 19:51

Bad Bad Bad The code is strictly for educational purpose i would advice you to get a book on basic Principles of Object Oriented programming

Making your variable static would make it accessible via the child class

class parentClass {
    public static $value = null;

    function __construct() {
        echo "patent called";
    }
}
class childClass extends parentClass {

    function sayIt() {
        var_dump(self::$value);
    }
}

$p = new parentClass();
parentClass::$value = 500;

$c = new childClass();
$c->sayIt();
查看更多
登录 后发表回答