php - __construct() vs 与类同名的方法

标签 php

我最近开始使用 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/

相关文章:

php - 在 div 中加载的页面的面包屑

php - 了解 ajax 画廊和类别

php - create-react-app 代理请求到 php 后端

php - 如何在php mysql中更新多个选择框的值

php - 图片无法在 PHP 中上传

php - Mysql联合查询重复行

php - 使用jwagener的recorder.js和recorder.swf将音频记录上传到服务器

php - 为什么不调用父构造函数?

php - PHP 中 TRIM 的不同行为

php - A-G、H-P、Q-Z之间如何拉取显示记录