Cod*_*4R7 4 php oop php-7 php-7.1 php-8
为了保持一致性,我从 PHP 7.1 开始为所有方法指定返回类型,包括像 这样的魔术方法__toString,甚至当隐式返回类型类似于voidwith时__unserialize():
class a {
function __toString() : string {}
function __unserialize ( array $data ) : void {}
function __wakeup() : void {}
}
Run Code Online (Sandbox Code Playgroud)
当我对构造函数和析构函数尝试相同时,如下所示:
class a {
function __construct() : void {}
function __destruct() : void {}
function __clone() : void {}
}
Run Code Online (Sandbox Code Playgroud)
PHP 产生Fatal errors:
Constructor a::__construct() cannot declare a return type
Destructor a::__destruct() cannot declare a return type
Clone method a::__clone() cannot declare a return type
Run Code Online (Sandbox Code Playgroud)
我现在唯一能做的就是在文档块中指定隐式返回类型,如下所示:
/**
* @return void (implicit)
*/
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么,因为其他预定义方法确实支持显式返回类型。我在文档或RFC中找不到任何有关此偏差的信息。
如何指定void构造函数和析构函数的返回类型?如果在 PHP 7 中不可能,那么在 PHP 8 中会成为可能吗?
构造函数和析构函数的概念是在 PHP5 中引入的。他们不明确返回任何内容。它们没有任何返回类型。
正如构造函数的定义所示,它用于创建作为类实例的对象。它用于初始化类的对象,因为构造函数声明看起来就像没有返回类型的方法声明。