如何指定构造函数的void返回类型?

问题描述 投票:-2回答:1

为了保持一致性,我指定了 返回类型 自PHP 7.1以来,所有的方法,包括神奇的方法,如 __toString的时候,甚至当隐式返回类型是 void__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)
 */

我不明白为什么,因为其他预定义的方法... 支持一个显式返回类型。我无法在 文献或在 指南针.

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

php oop php-7 php-7.1 php-8
1个回答
-1
投票

隐式返回类型的概念 ConstructorsDestructors引进PHP5. 它们没有明确地返回任何东西。它们没有任何返回类型。正如Constructor的定义,它用于创建一个类的实例对象。它用于初始化一个类的对象,因为构造函数声明看起来就像一个没有结果类型的方法声明。隐含地,它们返回的是类的当前实例。

© www.soinside.com 2019 - 2024. All rights reserved.