简体   繁体   English

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

[英]How to specify the void return type for a constructor

For consistency I'm specifying return types since PHP 7.1, for all methods, including magic ones like __toString , and even when the implicit return type is void like with __unserialize() :为了保持一致性,我指定了自 PHP 7.1 以来的返回类型,适用于所有方法,包括像__toString这样的魔术方法,甚至当隐式返回类型为void时,如__unserialize()

class a {
  function __toString() : string {}
  function __unserialize ( array $data ) : void {}
  function __wakeup() : void {}
}

When I try the same for constructors and destructors , like this:当我对构造函数和析构函数尝试相同的操作时,如下所示:

class a {
  function __construct() : void {}
  function __destruct() : void {}
  function __clone() : void {}
}

PHP yields Fatal error s: 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

The only thing I can do right now is to specify the implicit return type in a docblock like this:我现在唯一能做的就是在 docblock 中指定隐式返回类型,如下所示:

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

It puzzles me why, because other predefined methods do support an explicit return type.这让我感到困惑,因为其他预定义的方法确实支持显式返回类型。 I couldn't find anything about this deviation in the docs , or in the RFC .我在docsRFC中找不到任何关于这种偏差的信息。

How can I specify the return type void for constructors and destructors?如何为构造函数和析构函数指定返回类型void If it isn't possible in PHP 7, will it become possible in PHP 8?如果在 PHP 7 中无法实现,那么在 PHP 8 中是否可以实现?

The concept of Constructors and Destructors was introduced in PHP5. PHP5 中引入构造函数析构函数的概念。 They do not return anything explicitly.他们不明确返回任何东西。 They do not have any return type.它们没有任何返回类型。

As the definition of Constructor goes, it is used in the creation of an object that is an instance of a class.正如构造函数的定义所言,它用于创建 object,它是 class 的一个实例。 It is used to initialize an object of the class as the constructor declaration looks just like a method declaration that has no return type.它用于初始化 class 的 object,因为构造函数声明看起来就像没有返回类型的方法声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM