__construct() 与 SameAsClassName() 用于 PHP 中的构造函数
在 PHP 中使用 __construct()
代替类名对构造函数有什么好处吗?
Is there any advantage to using __construct()
instead of the class's name for a constructor in PHP?
示例(__construct
):
class Foo {
function __construct(){
//do stuff
}
}
示例(命名):
class Foo {
function Foo(){
//do stuff
}
}
从 PHP 5 开始就可以使用 __construct
方法(第一个示例).
Having the __construct
method (first example) is possible since PHP 5.
从 PHP 版本 4 到版本 7,可以使用与类同名的方法作为构造函数(第二个示例).
Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.
推荐答案
我同意 gizmo,优点是如果你重命名你的类,你就不必重命名它.干燥.
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.
例如,如果您将一个类插入到您的 heirachy 中,但忘记更改构造函数调用,您可以开始调用祖父母而不是父母的构造函数.这通常会导致可能难以注意到的不良结果.
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.
还要注意
从 PHP 5.3.3 开始,与命名空间类名的最后一个元素同名的方法将不再被视为构造函数.此更改不会影响非命名空间类.
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
来源:http://php.net/manual/en/language.oop5.decon.php
相关文章