问题描述
使用 __ construct()
而不是PHP中的构造函数的名称有什么优势吗?
Is there any advantage to using __construct()
instead of the class's name for a constructor in PHP?
example:
class Foo {
function __construct(){
//do stuff
}
}
或
class Foo {
function Foo(){
//do stuff
}
}
推荐答案
我同意gizmo,优点是,如果你重命名,你不必重命名你的班。 DRY。
I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.
同样,如果您有一个子类,您可以调用
Similarly, if you have a child class you can call
parent::__construct()
来调用父构造函数。如果进一步沿轨道你改变子类继承的类,你不必改变对父的结构调用。
to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.
这看起来像一个小东西,但是缺少将构造函数调用名称更改为父级类可能会创建微妙的(而不是那么微妙的)错误。
It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs.
例如,如果你在父类中插入一个类,但忘了改变构造函数调用,你可以开始调用祖父母的构造函数而不是父亲。
For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.
另请注意
源:
这篇关于__construct()vs SameAsClassName()用于PHP中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!