Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

The value of the void typehint in PHP

Original – 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)

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.


What are your thoughts on "The value of the void typehint in PHP"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.