Skip to content
Advertisement

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():

JavaScript

When I try the same for constructors and destructors, like this:

JavaScript

PHP yields Fatal errors:

JavaScript

The only thing I can do right now is to specify the implicit return type in a docblock like this:

JavaScript

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement