DEV Community

david duymelinck
david duymelinck

Posted on

Php features: parameter changes

As promised in my last post this one is about parameters

Theory

The biggest change is named parameters in php 8.0. This makes functions and class methods easier to use, less error prone and makes calling them self documenting.

A little change in php 8.0 is that you can add a comma after the last parameter. This is made because then you can follow the convention that is used for multi-line arrays.

Code

function a($b, $c = 1, $d = false,) {
  var_dump($b, $c, $d);
}
Enter fullscreen mode Exit fullscreen mode

Since php 5.6 you can do a(...['b']), but now you can do a(...['b' => 'b']).
You can write it shorter, a(b: 'b'). For the really lazy typers a('b') is still working.

The best usage is that you can skip parameters that have a default value. So you can do a(b: 'b', d: true) or a('b', d: true).

When you use the name there are several safeguards:

  • the name must exist. a(e: 'error')
  • you can't use a name multiple times. a(b: 'b', b: 'error')
  • named parameters must be after unnamed parameters a(d: true, 'b').

If you use all the parameters named the order doesn't matter, a(d: true, b: 'b').

Conclusion

Named parameters make the code easier to write and read. Because it is php 8.0 this also helps attributes.

Were you aware of the side effects of this change?

Top comments (0)