PHP 7.3 logo

What’s new in PHP 7.3

Yes, this is typical post about new features on a new version of PHP that 15% of PHP developers have in their personal blogs. To make it personal and unique, I will try to include multiple examples of the new features, so you can see how they can be applied in the real life.

1. JSON Exception

Until PHP 7.3, the only way to detect that a string contained a valid JSON was to check:

json_decode("{ This is not a valid JSON string");
json_last_error() === JSON_ERROR_NONE // the result is false

From PHP 7.3, an Exception will be thrown anytime a `json_decode` is not working. This Exception is JsonException and can be included in a try catch block, like this:

use JsonException;
 
try {
    $json = json_decode("{ This is not a valid JSON string");
    return $json;
} catch (JsonException $e) {
    // Do what you need
}

2. is_countable – New function

I’m pretty sure you have seen this error any time:

Warning: count(): Parameter must be an array or an object that implements Countable

The new function is_countable is here to help, because it helps you to check if something is countable, before using it in a loop. This is an example of its use:

$things = 123;
if(is_countable($thing)) {
  foreach($things as $thing) {
    
  }
}


3. Trailing commas allowed in function calls

Now we can use trailing commas in funcion calls. Before 7.3 it was only allowed to do this in arrays. From now on, it is possible to do it in function calls, but be aware! It is not yet possible in function definitions.

$result = getCOVIDTestResults(
    'PCR',
    $user,
);
  • Share post

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.