gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:29:31 25 4
gpt4 key购买 nike

我正在尝试以下操作:

//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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com