New PHP major versions are always very expected by PHP developers, we already know good things coming when a new release is announced. This time we have a lot of performance improvements and new features that improve our code, using modern programming methods in a badass old-school language.
Besides those new features and recommendations, I strongly recommend we use them only for environments that we can expect and have sure that 8.0 is running. In some cases, we can use polyfills instead. If you’re a plugin developer, it’s too soon to start using the new features of this version.
Nullsafe operator
I really love clean and efficient code, so I’m not a fan of the classic if/else statements (why we shouldn’t use them? Read more here). However, there is always a time when we need to use a simple if/then, and the best way to do that is using an inline if statement Like this:
$today_exists = time() ? true : false;
Clean, useful and works like a charm. I can’t know how many times I’ve tried to check a null value of a class method (for example), giving a “then” statement in the same line. Simple – it wasn’t possible, and the solution was based into split the statement into two or more lines.
The good news is called Nullsafe operator. PHP 8 now provides a null validation without any errors, so the following example now is pretty possible:
$today_exists = $this->get_time()?->$this->is_true();
str_contains() function
With this new function, we no longer need to use the strpos() function. This last one is more recognized by developers to be used to verify if a string contains a word, like this:
$today_exists = ( false !== strpos( 'Today is the day', 'Today' ) );
Yes, that’s what we had to do to check if a string contains X word 🙂
Checking the documentation, it’s really strange to see str_contains() only is available from 8.0. In this link, you can also find a pollyfill alternative.
New match() expression
That’s a good one for clean code. Imagine we have a switch case expression, but optimized to be used without breaks, and organized as a class sintax. I’m particullary interested into starting to use this new approach, check some examples in the documentation.
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
Enums
Exactly like other languages (e.g. javascript), enums provides us to call a function and have a definite number of cases on the args. The result is a more stable code. This one will be available in the 8.1 release only, but it’s a great example of what it’s happening with PHP – giving to the developers great native features we can use like a modern programming language.
I’m looking forward to use these features on my code, and I’m confident that will be possible soon – PHP 8.0 has been launched in November 2020, so please read more about WordPress and 8.0 compatibility before starting to code.
Leave a Reply