Mofiqul Islm Mofiqul Islm - 1 year ago 110
PHP Question

Parent class properties are null in child class in php

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download