php - 如何为构造函数指定 void 返回类型
问题描述
为了保持一致性,我从 PHP 7.1 开始为所有方法指定返回类型,包括魔术方法,__toString
甚至当隐式返回类型void
类似于 with 时__unserialize()
:
class a {
function __toString() : string {}
function __unserialize ( array $data ) : void {}
function __wakeup() : void {}
}
当我对构造函数和析构函数尝试相同的操作时,如下所示:
class a {
function __construct() : void {}
function __destruct() : void {}
function __clone() : void {}
}
PHP 产生Fatal error
s:
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
我现在唯一能做的就是在 docblock 中指定隐式返回类型,如下所示:
/**
* @return void (implicit)
*/
这让我感到困惑,因为其他预定义的方法确实支持显式返回类型。我在docs或RFC中找不到任何关于这种偏差的信息。
如何指定void
构造函数和析构函数的返回类型?如果这在 PHP 7 中是不可能的,那么它在 PHP 8 中会成为可能吗?
解决方案
PHP5中引入了构造函数和析构函数的概念。他们不明确返回任何东西。它们没有任何返回类型。
正如构造函数的定义所言,它用于创建作为类实例的对象。它用于初始化类的对象,因为构造函数声明看起来就像没有返回类型的方法声明。
推荐阅读
- express - JSON 有效负载中的 URL 导致 CORS 问题
- c++ - ReadFile 函数无法正确读取文件 - Win32 API
- python - 我没有收到附件
- database - 查找和替换数据库中的 URL,而不在 URL 末尾添加斜杠
- php - 在结帐页面(woocommerce)中将自定义字段插入数据库中的自定义表
- vba - 用于在表格中添加列表格式的命令按钮和文本框
- php - 如何使用 powershell 更改任务计划程序中的安全选项
- pine-script - 从特定时间开始如何使用barssince函数
- javascript - 如何在 reactjs 中每 5 分钟后调度一个动作
- docker-compose - 输入'CREATE TABLE没有可行的替代方案