“One of the nicest features that PHP affords is type hinting specifically for those who are coming from an object-oriented programming background.
From the PHP manual:
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
The reason this is important is because it gives people who are going to use your code – specifcally those who will write code against your code – what types of parameters a given constructor or function will accept.
But there’s more to it than that because type hints are also applicable to the type of data a function can return.
Nullable Return Types
For starters, let’s say that you have a function that’s supposed to return an object of some sort. In this example, let’s say that we have a
Post and the post is represented by a model. Naturally, the model is going to be of type post so the class signature will look something like this:
Now let’s say you have a secondary class that’s going to be returning an instance of the post. When using a type hint for the function, the signature would look something like this:
The thing is, the method may return a post or it may return
null if the model was never instantiated, passed into a given class, or simply doesn’t exist for some reason, then we need to account for that.
Case in point: If you’ve worked in WordPress in depth for any length of time, then you know that functions can return multiple things (like an instance of
WP_Error or an array). But in the purest object-oriented case that I’m talking about above, we’re looking at a function that may return
null or may return an instance of
And to indicate this, you can set up the method like this:
In short, adding the simple question mark before the object type says “This method may return null or an instance of
Or, more specifically from the PHP manual:
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type,
NULLcan be passed as an argument, or returned as a value, respectively.
So, yeah, this is a bit of a lengthy post to explain a straight-forward conept. But I find that using concrete examples is often more helpful than simply talking about it in the abstract.