DEV Community

david duymelinck
david duymelinck

Posted on

Php features: first-class callable syntax

As I mentioned in my previous post this is going to be a series.

This post is going to be a short one. But it made php code easier to read for me.

Theory

Php 8.1 introduced this syntax.

Before you wrote [$this, 'foo'] and from php 8.1 you can write $this->foo(...).

Routers in frameworks like Laravel and Symfony use the old way in their documentation. That is why I think a lot of people are still unaware of the new syntax.

Code

The syntax not only works on class methods, but also on functions. This means you can write $uppers = array_map('strtoupper', ['a', 'b', 'c']); now as $uppers = array_map(strtoupper(...), ['a', 'b', 'c']);.
You might complain about the three extra characters you need to type. For me it feels like you really calling a function instead of some magical string.

Another benefit for the class methods is that you can see if the method is static or not, because you can write My\Class::method(...) when your method is static. Which means you documented your code better without adding comments.

Conclusion

It is a little addition to the PHP syntax. But it makes the code more expressive for me.

For people who didn't know this, is it an improvement or do you feel indifferent about the change?

Top comments (0)