how to access parent variable from child class

2019-09-02 19:18发布

问题:

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

回答1:

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


回答2:

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.



回答3:

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.



标签: php oop class