我最近开始使用 php,想知道 __construct() 和具有与类同名的方法之间的区别?
有使用它的理由吗?我所能解决的只是它覆盖了名为 Foo 的方法,还是您更喜欢它?
例如
class Foo {
function Foo()
{
echo 'Foo stated<br>';
}
function __construct() {
echo 'Construct started<br>';
}
}
谢谢
最佳答案
使用 __construct()
是较新的 PHP5 更注重 OOP 的方法来调用构造函数。使用与类同名的方法是不推荐使用的旧方法,并且从 PHP 5.3.3 开始,它不会作为命名空间类的构造函数。
来自 the constructors and destructors page :
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.
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.
关于php - __construct() vs 与类同名的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3471731/