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()
:
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:
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:
/** * @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.
How can I specify the return type void
for constructors and destructors? If it isn’t possible in PHP 7, will it become possible in PHP 8 ?
Advertisement
Answer
The concept of Constructors and Destructors was introduced in 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. 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.