为什么我的PHP子类没有从父类获取公共和受保护的变量?
我有大脑冻结,我怀疑这是真的很简单。 考虑这个代码,有两个类:为什么我的PHP子类没有从父类获取公共和受保护的变量?,php,class,inheritance,Php,Class,Inheritance,我有大脑冻结,我怀疑这是真的很简单。 考虑这个代码,有两个类: <?php class myparentclass { protected $vara; private $varb; public $varc; public $_childclass; function __construct() { $this->vara = "foo"; $this->varb = "bar";
<?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();
我知道不应该设置$varb,但是其他的呢?您必须在子类构造函数中调用父类构造函数
class mychildclass extends myparentclass {
function __construct() {
// The parent constructor
parent::__construct();
print_r ($this);
}
}
function __construct() {
parent::__construct();
print_r ($this);
}
如果您在子类中定义了一个新的
\u construct()
,就像您打印变量一样,那么您也需要显式调用父类的构造函数。如果未在子类中定义任何\u construct()
,则它将直接继承父类的,并且所有这些属性都已设置
parent::__construct();
如果子类有自己的构造函数,则必须从其中显式调用父构造函数(如果希望调用它):
如果在子类中重新定义构造函数,则必须调用父构造函数
class mychildclass extends myparentclass {
function __construct() {
// The parent constructor
parent::__construct();
print_r ($this);
}
}
function __construct() {
parent::__construct();
print_r ($this);
}
应该可以正常工作。您的父构造函数从不由子构造函数执行。按如下方式修改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();
您正在用父类中的构造函数重写父类的构造函数。可以使用parent::\u construct()从子类调用父类的构造函数 然而,myparentclass构造函数的最后一行调用mychildclass构造函数,后者反过来调用父构造函数,等等。你是想达到这个目的吗
告诉过你这很简单+1好的,谢谢。
<?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();