I have two classes in PHP when I inherit one class from another the properties of parent class are available in child class but their value is null.
Parent Class:
<?php
class Parent_class {
public $foo;
public $bar;
public function __construct(){
$this->foo = 'This is foo';
$this->bar = new self();
}
public function getFoo(){
echo 'Foo is: ' .$this->foo;
}
public function getBar(){
echo 'Bar is :' .$this->bar;
}
}
Child Class :
<?php
require './class1.php';
class Child_class extends Parent_class{
public function __construct(){
echo $this->foo;
print_r($this->bar);
var_dump(get_object_vars($this));
}
}
$child = new Child_class();
$child->getFoo();
$child->getBar();
Result :
array(2) {
["foo"]=>
NULL
["bar"]=>
NULL
}
Foo is: Bar is :
So, How can I get those value in child class to. Did I made something wrong here?
You actually override you parent constructor. Try this
public function __construct()
{
parent::__construct();
echo $this->foo;
print_r($this->bar);
}
Or better if you will output your data via some method, not constructor.
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.