为什么PHP不会自动调用父构造函数? [英] Why does PHP not automatically call parent constructors?
问题描述
相当直截了当的问题。在C ++中,父构造函数将在子构造函数之前被隐式调用,那么PHP有什么逻辑不以这种方式做事?
Fairly straightforward question. In C++ the parent constructor will be implicitly called before the child constructor, so what logic is there for PHP not to do things this way?
编辑:强烈>我从Lukman得到了一个很好的答案,但我希望有更多的原因可以解决这个问题。也许问题应该是为什么C ++不允许自定义调用父构造函数?我想这是另一个问题。
I've got a good answer from Lukman, but I was hoping for more of a reason why there is a difference. Maybe the question should be why does C++ not allow custom calling of parent constructors? I guess that's another question though.
推荐答案
我认为PHP让你手动调用parent的构造函数是件好事,因为它允许child的构造函数如下:
I think it's a good thing that PHP makes you call parent's constructor manually, because it allows child's constructor such as following:
public function __construct() {
// set up variables that parent::__construct() requires
$var1 = get_stuff_from_db();
$var2 = get_stuff_from_webservice();
parent::__construct($var1, $var2);
// continue setting up $this var
$this->default = 'Default';
$this->do_some_secret_stuff();
}
甚至:
public function __construct($param) {
// call differently based on condition
if (is_array($param))
$param['id'] = 0;
parent::__construct($param);
}
else {
parent::__construct($param, 0, TRUE);
}
// continue setting up $this var
$this->default = 'Default';
$this->do_some_secret_stuff();
}
意思是,您可以在孩子的任何地方调用父构造函数在通话前后都可以自由地做事。这不是一个功能吗?
Meaning, you are free to call the parent constructor anywhere within the child's and you are free to do stuff before and after the call. Ain't that a feature indeed?
这篇关于为什么PHP不会自动调用父构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!