Skip to main content

Named arguments add context

A couple of weeks ago, I wrote that using types adds context to code, making it easier to read and understand.

Something else that also adds context is named arguments, which were introduced to PHP in version 8.0.0.

I particularly like them when making assertions within tests, where getting the expected and actual values in the wrong order can create some confusing output.

For example:

self::assertSame(expected: 'My Drupal website', actual: $node->label());

While I can tell from the assertion that I'm checking two values are the same, adding the argument names makes it clear which is the expected value and which is the actual value.

In fact, if you use named arguments, the order no longer matters, so I can put them in whichever order I want and it will work the same way.

Was this interesting?

Subscribe to my daily newsletter for software professionals on software development and delivery, Drupal, DevOps, community, and open-source.

About me

Picture of Oliver

I'm a certified Drupal Triple Expert and former Drupal Association staff member with 18 years of experience, a Drupal core contributor, public speaker, live streamer, and host of the Beyond Blocks podcast.