★ The value of the void typehint in PHP
Freek Van der Herten
Posted on January 2, 2020
When the void
typehint was introduced in PHP 7.1. There was some debate about it. Some people wondered if it is beneficial to type nothing? I was one of them. Meanwhile, I changed my opinion on it. In this short post, I'd like to give you a small example where I think void
shines.
This is the example given in the Laravel documentation on local model scopes.
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
That return
statement is a lie. Nothing is done with the result.
The given Builder
instance in $query
is mutable. In PHP, objects are being passed by reference. This means that the $query
object in scopePopular
is shared with the code that calls scopePopular
. By calling where
on it, the $query
will change both for scopePopular
as the code that calls it.
In my projects, I would write the scope above like this:
public function scopePopular(Builder $query): void
{
$query->where('votes', '>', 100);
}
To me, this is more honest. The void
typehint signals to me (and I hope to my team members as well) that there is no point in returning something, and that (in this case) the given parameter likely is mutable.
(Thanks for proofreading this, Brent)
Posted on January 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.