PHP中在子构造函数之前调用父构造函数 [英] Call parent constructor before child constructor in PHP
问题描述
我想知道是否可以在使用 PHP 继承的孩子的 __construct() 之前调用父母的 __construct().
I was wondering if its possible to call the parents __construct(), before the child's __construct() with inheritance in PHP.
示例:
class Tag {
__construct() {
// Called first.
}
}
class Form extends Tag {
__construct() {
// Called second.
}
}
new Form();
理想情况下,我可以在它们之间做一些事情.如果这是不可能的,是否有替代方法可以让我这样做?
Ideally, I would be able to do something in between them. If this is not possible, is there an alternative, which would allow me to do this?
我想这样做的原因是为了能够加载一堆特定于在调用 __construct() 时表单可以使用的标签的默认设置.
The reason I want to do this is to be able to load a bunch of default settings specific to the Tag that Form can use when __construct() is called.
抱歉忘了添加这个..我宁愿不从子类调用父类.这仅仅是因为当您将其作为参数传递时,它会向孩子公开一些私有数据(对于父级)
这就是我想要做的:
$tag = new Tag($privateInfo, $publicInfo);
$tag->extend(new Form()); // Ideal function, prob doesn't work with inheritance.
Tag.php
class Tag {
private $privateInfo;
public $publicInfo;
__construct($private, $public) {
$this->privateInfo = $private;
$this->publicInfo = $public;
}
}
Form.php
class Form extends Tag {
__construct() {
echo $this->publicInfo;
}
}
有意义吗?
谢谢!马特·穆勒
推荐答案
只需在孩子中调用 parent::__construct 即可.
Just call parent::__construct in the child.
class Form extends Tag
{
function __construct()
{
parent::__construct();
// Called second.
}
}
这篇关于PHP中在子构造函数之前调用父构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!