Sevalla is the all-in-one PaaS for your web projects. Host and deploy your applications, databases, object storage, and static sites. Enjoy advanced deployment pipelines, a complete database studio, instant preview apps, and one-click templates. The pricing is simple: no hidden fees, no seat-based pricing, and you pay only for what you use. Get real human support from developers.

Get started now with a $50 credit at Sevalla.com.

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.