【发布时间】:2020-09-10 04:08:03
【问题描述】:
为了保持一致性,我从 PHP 7.1 开始为所有方法指定 return types,包括像 __toString 这样的魔术方法,即使隐式返回类型是 void,就像 __unserialize() 一样:
class a {
function __toString() : string {}
function __unserialize ( array $data ) : void {}
function __wakeup() : void {}
}
当我对constructors and destructors 尝试相同的操作时,如下所示:
class a {
function __construct() : void {}
function __destruct() : void {}
function __clone() : void {}
}
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
我现在唯一能做的就是在这样的文档块中指定隐式返回类型:
/**
* @return void (implicit)
*/
我很困惑为什么,因为其他预定义的方法确实支持显式返回类型。我在the docs 或the RFC 中找不到有关此偏差的任何信息。
如何为构造函数和析构函数指定返回类型void?如果在 PHP 7 中无法实现,那么在 PHP 8 中是否可以实现?
【问题讨论】:
-
构造函数和析构函数不(也不能)返回任何东西,那么他们为什么要支持它呢?这将毫无意义。
-
构造函数不会显式返回任何内容。它们没有返回类型。
-
构造函数返回其类的类型。这从 PHP 7.4(或者可能是 7.3)开始有效。
-
构造函数返回
void为per documentation。创建对象后,调用构造函数来初始化对象。我的观点是你不能自己指定返回类型void,这与泛型方法声明不一致。就像无法在公共方法上指定public关键字一样,因为它们默认是公共的,您唯一的选择是protected和private。 -
@MagnusEriksson 为了语法简洁起见,应该支持它,正如 Swatantra Kumar 发现的此错误报告 bugs.php.net/bug.php?id=75263 中所述。可以这样想:为什么
__construct()的魔术函数与__unserialize()有什么不同?
标签: php oop php-7 php-7.1 php-8