PHP 命名空间和构造函数问题

标签 php constructor namespaces

我正在尝试以下操作:

//file1.
namespace foo;
class mine {
     public function mine() {
         echo "Does not work!!";
     } 
}
//file2. 

use foo/mine;
include "foo/mine.php";
$obj = new mine();

上面的场景是行不通的。没有错误,包括文件——构造函数没有被调用。

然而,当我使用 __constructor() 时,一切正常。我正在使用 php v5.4

最佳答案

来自 php manual :

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent 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.

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.

您可以使用类的名称作为构造函数(除非该类是命名空间的)因为 PHP5 保留它是为了与 PHP4 向后兼容,但不推荐这样做,因为它是旧方法并且可能会在较新版本的 php 中被删除.因此,除非您正在编写出于某种原因需要与 PHP4 兼容的内容,否则请使用 __construct()

关于PHP 命名空间和构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23431268/

相关文章:

php - Laravel 列表 concat 不显示数据(全名)

c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?

php - mysqli 将位和整数作为字符串返回

php - 将 mysql 数据库中的多行存储到一个变量中

php - 将复选框值发送到 php 脚本以通过 jquery 进行处理

c# - 为什么向我的实体模型类添加无参数构造函数在这里起作用?有什么影响?

Java深度克隆问题

PHP Doctrine 与命名空间的关系

c# - 使用嵌套命名空间

xml - 如何使用 xquery 从 xml 文件中读取 namespace