gpt4 book ai didi

php - 如何为构造函数指定 void 返回类型

转载 作者:行者123 更新时间:2023-12-05 01:36:27 25 4
gpt4 key购买 nike

为了保持一致性,我指定了 return types自 PHP 7.1 起,适用于所有方法,包括像 __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 error :

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

我现在唯一能做的就是像这样在文档 block 中指定隐式返回类型:

/**
* @return void (implicit)
*/

这让我感到困惑,因为其他预定义方法确实支持显式返回类型。我在 the docs 中找不到有关此偏差的任何信息,或在 the RFC .

如何为构造函数和析构函数指定返回类型void?如果在 PHP 7 中不可行,那么在 PHP 8 中是否可行?

最佳答案

构造函数析构函数的概念是introduced在 PHP5 中。他们没有明确返回任何东西。它们没有任何返回类型。

按照构造函数的定义,它用于创建作为类实例的对象。它用于初始化类的对象,因为构造函数声明看起来就像没有返回类型的方法声明。

关于php - 如何为构造函数指定 void 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61969897/

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