首页 > 解决方案 > 如何为构造函数指定 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 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

我现在唯一能做的就是在 docblock 中指定隐式返回类型,如下所示:

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

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

如何指定void构造函数和析构函数的返回类型?如果这在 PHP 7 中是不可能的,那么它在 PHP 8 中会成为可能吗?

标签: phpoopphp-7php-7.1php-8

解决方案


PHP5中引入了构造函数析构函数的概念。他们不明确返回任何东西。它们没有任何返回类型。

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


推荐阅读