Reputation: 1173
I have found no information about this in the documentation, but it seems logical to exist. How to make a type hinting for a returning a value of object
type? (I'm talking about any object, not a certain object of for instance \DateTime
etc.)
function getParticipant(): ?object
{
//...
$x = new Cat();
return $x;
}
It is not working and what is really unfair is that print getType($x)
will result in object
. So we have an object
type but can't say strictly that we will return an object
?
You may say that it is really not necessary and I could have just written : Cat
, but that's not what I need when I overwrite a method which has got * @return object|null */
in his PHPDoc.
Upvotes: 2
Views: 3053
Reputation: 212522
Type-hinting for a generic object
doesn't yet exist in PHP, but should be available from version 7.2.0 onwards as a result of RFC Object typehint which passed by 32 votes to 3 on 31st May 2017.
Although normally (where possible) it is still better to type-hint to a specific class or interface.
Upvotes: 5
Reputation: 27325
I can't find an exact explanation but at the moment you can return Classes, scalar values and since PHP 7.1 you have void
as return value. But in your case "object" as return value doesn't exist.
And in my eyes it make a lot more sense to check which object you return to be clear that you return the correct object. So in your case:
function getParticipant(): Cat
{
//...
$x = new Cat();
return $x;
}
Then you can be sure that your function return the object you expect.
Upvotes: 1
Reputation: 1624
:object
does not resolve for variables which have this type. In fact, PHP will look for class named object
and expect that instance of this class will be returned.
Using your example you should indicate that function will return an instance of Cat
so it should look like this:
function getParticipant(): Cat
{
return new Cat();
}
I'd say that it's fine that PHPDoc says that object
will be returned. IDE's should resolve it and for PHP interpreter it doesn't matter.
In case you're overwriting method you can simply overwrite @return
statement in PHPDoc.
Upvotes: 1