New Features of PHP 7.3 [Complete Guide]
In this post, you will learn what features will be implemented in the new PHP 7.3 and how they help developers write better code.
Join the DZone community and get the full member experience.
Join For FreeFollow the Series
You can check the other blog posts following the links below:
New Features
JSON_THROW_ON_ERROR
Not having an adequate way to handle errors when using JSON has been a problem for quite a long time, and web developers all over the world have seen this as a huge downside of the language,
The RFC of PHP 7.3 has accepted this update by a 23-0 vote, which shows how much this feature has been requested.
Until PHP v7.2, we needed to use a workaround to get an error from JSON and it was neither reliable nor proficient at its job.
Here is an example:
json_decode("{");
json_last_error() === JSON_ERROR_NONE // the result is false
json_last_error_msg() // The result is "Syntax error"
Yes, we can determinate if our JSON had an error, but, this is clearly not the best method to do so.
The new flag I am about to show you is an excellent alternative because it gives programmers the opportunity to use the power of exceptions that can be managed within the “try-catch” block of code.
Let’s see a practical example, shall we?
use JsonException;
try {
$json = json_encode("{", JSON_THROW_ON_ERROR);
return base64_encode($json);
} catch (JsonException $e) {
throw new EncryptException('Could not encrypt the data.', 0, $e);
}
As you can see from the previous code block, the json_encode
function now has an optional parameter JSON_THROW_ON_ERROR
which will catch the error and display it using the following exception methods:
$e->getMessage(); // like json_last_error_msg()
$e->getCode(); // like json_last_error()
The default adaptation of PHP 7.3 toward your existing code will be neutral and since it is an optional parameter after you update your PHP everything will still work as aspected.
This is one of the most important features of the update, so if you want to dig in and learn more have a look at the official RFC for JSON_THROW_ON_ERROR
is_countable
A countable element in your code can be a variable with an array format or an object whose class is implementing the countable interface.
Last year, PHP 7.2 added a warning that shows up whenever a developer was counting or trying to loop an uncountable element.
It is possible to solve this problem and one of the best solutions currently used is to apply a check like a snippet below:
if (is_array($santa) || $santa instanceof Countable) {
// $santa is countable
}
The code checks whether the variable is an array or is an instance of the Countable interface.
And it will work but it seems a little bit “crowded” and, as many of you that work long hours, after a while seeing these kinds of lines wears your eyes out.
The team that is developing the new version took account of this and added a new function that will help the web developer immensely.
The is_countable
function takes a variable as a parameter and then returns a boolean depending on if the function is countable or not.
There is no restriction about the format the parameter has to be, of course, if you put a non-countable variable the return will be false.
Let’s see it in practice:
if (is_countable($santa)) {
// $santa is countable
}
This snippet basically does the same thing as the previous one but is much easier to remember and, most importantly for me, more readable.
Not to mention you can use this function as shown or in a ternary conditional operator which will look even more satisfying.
For more information about is_countable have a look at the official RFC
array_key_first(), array_key_last()
As per version 5.6 of PHP, there are over 75 built-in functions that belong to the arrays category.
Despite the vast numbers of tools available, at the moment, if we need to retrieve the first or the last key of an array we have to get all the keys using array_keys()
and only then go for the first or last values of the array.
Another way is to opt for end()
or reset()
.
As you may know, all the methods just described modify the array pointer, which is something that (other than a resources consumer) you just may not want to do.
The RFC of the upcoming version proposed the introduction of four brand-new methods the were set to solve this issue.
The four methods were:
array_key_first()
array_key_last()
array_value_first()
array_value_last()
They work for both numeric and associative arrays.
Here is some example of a numeric one:
$reindeers = [
1 => "Rudolph",
2 => "Dasher",
3 => "Dancer",
4 => "Prancer",
5 => "Vixen",
6 => "Comet",
7 => "Cupid",
8 => "Donner",
9 => "Blitzen"];
$first = array_key_first($reindeers); // $first is equal to 1
$last = array_key_last($reindeers); // $last is equal to 9
This, instead, is an example of an associative array:
$reindeers = [
"Rudolph" => 1,
"Dasher" => 2,
"Dancer" => 3,
"Prancer" => 4,
"Vixen" => 5,
"Comet" => 6,
"Cupid" => 7,
"Donner" => 8,
"Blitzen" => 9];
$first = array_key_first($reindeers); // $first is equal to "Rudolph"
$last = array_key_last($reindeers); // $last is equal to "Blitzen"
The same would have worked for the other two functions illustrated in this chapter, array_value_*
.
Just to be clear, those functions have been refused with 18 nos and 15 yeses.
In my opinion, these two functions would have been useful as well but according to several web developers, in certain cases, the value returned would have been ambiguous.
Here is why:
$reindeers = [];
$first = array_value_first($reindeers ); // $first is equal to null
$last = array_value_last($reindeers );// $last is equal to null
An additional option that I came across while browsing on forums and talking to other web developers was to return a tuple like [$key => $value]
.
Even though this option will not be available on the new version, seeing the favorable responses, it might arrive with the following RFCs.
Since this is a function that did not exist before, there are not going to be any backward compatibility problems, the only issues arrive if you have created and you are using your own version of array_key_first()
and array_key_last()
.
Same Site Cookie
Deploying a secure application must always be the main focus of every programmer.
One task that each of us is facing on a daily basis is to diminish the risk of CSRF and data leak attacks.
Same-site cookies declare that cookies must be sent only with a request initiated from the same domain.
This is not an official standard but Google Chrome and several of the best PHP frameworks already implement it whereas Firefox and new version of other frameworks confirmed that they are planning to do so.
Here is the support schema for same site cookie from caniuse.com
Currently, cookies are issued by the set-cookie header, and web developers can set a key-value pair alongside flags for the browser in order to agree if a cookie should be available or not.
This way of doing things allows for vulnerable access to CSRF attacks.
The new RFC additions are supposed to solve the problem in a non-breaking way by adding a new parameter and also modifying some main functions of the language.
setcookie
setrawcookie
session_set_cookie_params
setcookie($name [,$value [,$expire [,$path [,$domain [, $secure [,$httponly [,$samesite]]]]]]]);
Two ways were proposed.
Adding a new argument to the function or allowing an array of options for moving all the options of the cookies inside.
How it will work?
Two values can be added to the same-site flag present in the above functions
They are Lax and Strict.
Cookies that are using Lax will be accessible to a GET request that comes from another domain, while on the contrary Strict will not be accessible ti a GET request.
For instance, the header, when using the Lax flag, will look like this:
Set-Cookie: key=value; path=/; domain=example.org; HttpOnly; SameSite=Lax
Including features that increase security in the code seems like a no-brainer but, as always, before deciding to apply them in our scripts we need to properly evaluate the pros and the cons of our choices
The main risk of using the SameSite flag as a supplementary argument to those functions is that it might never become an official standard.
This means that, eventually, browsers will not accept the flag.
If this happens and you have already implemented it, it will result in your applications being stuffed with junk code that needs to be removed.
My personal advice is to wait to see what is going to happen. If this flag becomes more used and eventually defined as a standard, go for it!
Speaking of backward compatible changes, like most of the previous changes seen in this article, there will be no problem when implementing it in your code.
Conclusion
As I anticipated, this new release does not involve breaking changes, since it’s not a new version; which I believe is the right way to make updates.
PHP is taking small but continuous steps that allow it to progress and improve over time despite the fact that over the years people have changed to more trendy programming languages.
In the next post, you will see other miscellaneous changes and a list of features no longer in use that have finally been deprecated to make room for new projects.
This blog post is a section of the Kindle book “PHP 7.3 and its Christmas gifts.”
Now It’s Your Turn
Now I want to hear from you.
Are you happy with the new feature brought by the language? What are you going to use more often?
Let me know by leaving a quick comment below.
Published at DZone with permission of Nico Anastasio. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments