The value of the void typehint in PHP - Freek Van der Herten's blog on PHP, Lara...
source link: https://freek.dev/1481-the-value-of-the-void-typehint-in-php
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
The value of the void typehint in PHP
Original – Oct 11th 2019 by Freek Van der Herten – 2 minute read
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)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK