php中的子类中的父类属性为null

时间:2017-07-26 13:57:04

标签: php

当我从另一个类继承一个类时,我在PHP中有两个类,父类的属性在子类中可用,但它们的值为null。

父类:

    <?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;
  }
}

儿童班:

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

结果:

 array(2) {
  ["foo"]=>
  NULL
  ["bar"]=>
  NULL
}

Foo is: Bar is :

那么,我怎样才能在子类中获得这些值。我在这里搞错了吗?

1 个答案:

答案 0 :(得分:2)

你实际上覆盖了你的父构造函数。试试这个

  public function __construct()
{
    parent::__construct();
    echo $this->foo;
    print_r($this->bar);
}

或者更好的是,如果您将通过某种方法输出数据,而不是构造函数。