为什么我的PHP子类没有从父类公开并受保护的var?

问题描述

| 我正在冻结,我怀疑这真的很简单。 考虑以下代码,其中包含两个类:
<?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,但是其他的呢?     

解决方法

如果您已经在子类中定义了一个新的ѭ2,以打印出var,那么您还需要显式调用父类的构造函数。如果您在子类中未定义任何“ 2”,它将直接继承父类的所有那些属性。
class mychildclass extends myparentclass {
  function __construct() {
    // The parent constructor
    parent::__construct();
    print_r ($this);
  }
}
    ,您必须在子类构造函数中调用父类构造函数。
function __construct() {
        parent::__construct();
        print_r ($this);
    }
    ,如果在子类中重新定义构造函数,则必须调用父构造函数。
class mychildclass extends myparentclass {
 function __construct() {
     parent::__construct();
     print_r ($this);
 }
}
应该工作正常。     ,如果子类具有其自己的构造函数,则必须从其内部显式调用父构造函数(如果要调用它):
parent::__construct();
    ,您的父级构造函数永远不会由子级执行。像这样修改mychildclass:
function __construct() {
    parent::__construct();
    print_r ($this);
}
    ,您正在使用父类中的构造函数覆盖父类的构造函数。您可以使用parent :: __ construct();从子类中调用父级的构造函数。 但是,myparentclass的构造函数的最后一行调用mychildclass的构造函数,而mychildclass依次调用父构造函数,等等。您是要实现这个目标吗?
<?php    
class myparentclass {
    protected $vara;
    private $varb;
    public $varc;

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

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

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