简体   繁体   中英

PHP : Class Extends

I have made some example code to explain my question:

class Core {
   public $test = null;
   public function __construct(){
       $this->test = "hi";
   }
}

$data = new Core;

class Extension extends Core {
    public function __construct(){
        $this->test = "hello";
    }
}

$data->ext = new Extension;

echo $data->test . "<br />";
echo $data->ext->test;

Which outputs as:

hi
hello

My question is hard to explain but I am just wondering if there was a way to overwrite the $test variable in the parent class within the child class so:

echo $this->test; would output "hello" since it changed in the child class.

Is there a way of doing this or can the child not access/change the parent variables?

Use a static property for your use case.

Check here http://php.net/manual/en/language.oop5.static.php , the second example should help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM