Named Arguments and Union Types in PHP 8.0

I am itching to get my hands dirty on PHP 8.0 that was released last week.  Unfortunately, I cannot make the big jump immediately but there are some language improvements that I am looking forward to using.  New to PHP 8 are Named Arguments and Union Types.

Named Arguments

As an example, function htmlspecialchars only requires the first parameter.  The rest are optional with the default value of the 4th argument being true.  Previously, if you wished to code false for the value of the 4th argument you would have written code similar to this:

In PHP 8 you can now use named arguments just to target optional parameters you wish to set.

Not only are you not having to worry about specifying values for the 2nd and 3rd arguments when the default values suffice but by using the named argument, in this case, double_encode, your code becomes more readable by clarifying the purpose of that argument.

If, like myself, you often work on code written by other developers, when reverse-engineering and modifying the code you can now add the named parameters to aid clarity.  Saving you more time and effort the next time you visit that same code which could be months or years in the future.

There are, at times, you come across code with good variable names which aid clarity and improve the code’s readability.  For example:

In the above example, the first three variables are named after their data type or purpose. However, it is unclear as to what the purpose of the 4th argument is. In PHP 8 you can now make it clearer for yourself and others by using a named argument

If you working, as exampled below with poorly named  variables or with hardcoded values, you could go the whole hog and name all the arguments:

Union Types

Type declarations existed prior to PHP 8 and over 5 years ago a proposal to introduce union types was declined.  This left a gap for code that supports multiple types but was left with poorer type safety checking from PHP’s run-time engine.

For example, if you have a parameter that accepts multiple types such as an integer or a float you could not specify that in a type-safe way. As a result calling code could pass a string (due to, for example, a coding typo) and it could run without complaint or no obvious bug.

Previously you may have coded your function definition and call as:

But, what is the behaviour of this code if $myVariable was a string? Your code has undefined behaviour and potentially unpredictable behaviour too.

With the introduction of union types the function definition can be explicit:

Now, if a string is passed to our function the PHP engine will raise a TypeError.  You can view more about union types from the RFC that was proposed and accepted for introducing into PHP 8.0.

Leave a Reply

Your email address will not be published. Required fields are marked *