php - 为什么我的 PHP 子类没有从父类获得公共(public)和 protected 变量?

标签 php class inheritance

我正在接受 brainfreeze,我怀疑这个真的很简单。 考虑这段代码,有两个类:

<?php    
class myparentclass {
    protected $vara;
    private $varb;
    public $varc;
    public $_childclass;

    function __construct() {
        $this->vara = "foo";
        $this->varb = "bar";
        $this->varc = ":(";
        $this->_childclass = new mychildclass;    
    }
}

class mychildclass extends myparentclass {
    function __construct() {
        print_r ($this);
    }
}

print "<pre>";
$foo = new myparentclass();

输出是:

mychildclass Object
(
    [vara:protected] => 
    [varb:private] => 
    [varc] => 
    [_childclass] => 
)

我知道不应该设置 $varb,但是其他的呢?

最佳答案

如果像打印变量一样在子类中定义一个新的 __construct(),则还需要显式调用父类的构造函数。如果您没有在子类中定义任何 __construct(),它将直接继承父类,并且所有这些属性都会被设置。

class mychildclass extends myparentclass {
  function __construct() {
    // The parent constructor
    parent::__construct();
    print_r ($this);
  }
}

关于php - 为什么我的 PHP 子类没有从父类获得公共(public)和 protected 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6124920/

相关文章:

php - 在php中使用父类或命名空间访问继承的类

php - php/mysql 查询的计数和求和

php - 推荐网站没有被网络服务器重写

php - PHP中静态类的不同实例

php - 拾色器不保存值

html - 为什么一些一次性使用的元素在 CSS 中是 Class 而不是 ID?

java - 将 System.out.format 翻译成 Clojure

c++定义继承方案

C++11删除重写方法

javascript - javascript 超出最大调用堆栈大小