At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

What's New In PHP 7.3? Explore The Latest Updates Of PHP 7.3

  • By Harikrishnan R
  • November 21, 2018
  • 922 Views

 

What’s New In PHP 7.3?

PHP 7.3 recently released and it’s newly updated features getting huge attention among the developers due to it’s convenient updates, Also all the notable features in PHP 7.3 are intended to increase of performance and security of the application. So today we’re very much excited to highlight the new features of PHP 7.3 with you all. Let’s have a quick glance on each feature.

  • Json_throw_on_error
  • Allow a trailing comma in function calls
  • Flexible Heredoc and Nowdoc Syntaxes
  • PCRE2 Migration
  • list() Reference Assignment
  • Remove and Deprecate image2wbmp()
  • is_countable() function
  • array_key_last(),array_key_first()
  • Same Site Cookies
  • Argon2 Password Hash Enhancements
  • Remove and Deprecate Case-Insensitive Constants

 

Json_throw_on_error

For parsing JSON responses, we already have two functions ie.., json_encode() and json_decode(). But the problem with those functions are that we don’t have proper error throwing mechanism. Json_decode will throw null, and null can be true value where as Json_encode() will throw only false errors. So in most of the cases, we handled the errors only by calling json_last_error() or json_last_error_msg() and also that’s the only way we have.
But the new version got a solution for us, now just by adding JSON_THROW_ON_ERROR in both functions we can solve this issue which will completely ignore the global error state.
Ex:

json_encode($data, JSON_THROW_ON_ERROR);
json_decode("invalid json", null, 512, JSON_THROW_ON_ERROR);

pcre2 Migration

PHP 7.3 uses the PCRE2, on older versions we were using the PCRE for regular expressions on which we’re asked to migrate our existing regerx according to the new rules but these rules are far better then what had before.
Let’s see it with an example.

preg_match('/[\w-.]+/', '');

This regex will now fail and will not show a warning message or error, it is because PCRE2 is escaping from this work or very strict about moving hyphen to the end.

list() Reference Assignment

In PHP we already had list() assignment and reference assignment functions. But in later versions we’re not allowed to use reference assignment in a list() where as in latest PHP 7.3 version we can able to use it with proper syntax.

$array = [1, 2];
list($a, &$b) = $array;
$array = [1, 2];
list($a, &$b) = $array;

This is equal to below form:

$array = [1, 2];
$a = $array[0];
$b =& $array[1];
$array = [1, 2];
$a = $array[0];
$b =& $array[1];

In PHP 7.3 updates will allow us to use this feature with a nested list and the foreach() function looks like this,

$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
  $a = 7;
}
var_dump($array);
$array = [[1, 2], [3, 4]];
foreach ($array as list(&$a, $b)) {
  $a = 7;
}
var_dump($array);

 

Allow a Trailing Comma in Function Calls

This feature will append the trailing commas which are given at the last of the listed variables, parameters, and elements. Very often, we were in a situation to call several elements from an array or from specific function and by any chance, if we miss the comma then its definitely gonna hit us with sequence of errors. On overcoming these problems, the current feature help us to use the trail commas which we can use it on arrays and also can use it from PHP 7.2 grouped namespace syntax onwards.

unset(
  $foo,
  $bar,
  $baz,
);

Similarly, we can pass list of variables to template engine through compact() function and here is the quick sample for you.

echo $twig->render(
  'index.html',
  compact(
      'title',
      'body',
      'comments',
  )
);

Sometimes we need array_merge() to append two arrays and in some case we need to group data so in that case we can use trailing commas like these,

$newArray = array_merge(
  $arrayOne,
  $arrayTwo,
  ['foo', 'bar'],
);

Similarly , you can also use function’s arguments in these methods.

class Foo
{
public function __construct(...$args) {
  //
}
public function bar(...$args) {
  //
}
public function __invoke(...$args) {
  //
}
}
$foo = new Foo(
'constructor',
'bar',
);
$foo->bar(
'method',
'bar',
);
$foo(
'invoke',
'bar',
);

is_countable function

Previously, we use to count arrays and objects via count() function, but do you remember the problem we faced in counting, Obviously the object will not be counted sometimes then that will throw us a warning message. So we ought to check whether the variable or object is counted or not. From PHP 7.3 has a is_countable() function which will return passed variable only when its countable.
So we have a new type of function that returns true if the given value is an array type.
In older version:

if (is_array($foo) || $foo instanceof Countable) {
  // $foo is countable
}

In current version:

if (is_countable($foo)) {
  // $foo is countable
}

In older versions:

if (is_array($foo) || $foo instanceof Countable) {
  // $foo is countable
}

In current version:

if (is_countable($foo)) {
  // $foo is countable
}

array_key_first(), array_key_last()

Current version of PHP allows us to get last value or array first key just by changing the current state of the array using various functions like end(), reset()and key() functions. In PHP 7.3 we have new methods for performing these functions,

  • $value = array_value_last($array); To gather last value of array
  • $key = array_key_first($array); To gather first key of array
  • $value = array_value_first($array); To gather first value of array
  • $key = array_key_last($array); To gather last key of array

We can go through an example

// usage of an associative array
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 'a');
assert($lastKey === 'c');
// usage of a numeric array
$array = [1 => 'a', 2 => 'b', 3 => 'c'];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 1);
assert($lastKey === 3);
// usage of an associative array
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 'a');
assert($lastKey === 'c');
// usage of a numeric array
$array = [1 => 'a', 2 => 'b', 3 => 'c'];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 1);
assert($lastKey === 3);

 

Related: Implementing The Best PHP Coding Standard And Practices In CodeIgniter

 

Flexible Heredoc And Nowdoc Syntaxes

Heredoc and Nowdoc syntax will allow us to use multi-line long strings. It needs an identifier which will be the ending identifier and then the first string should appear in new line.
In the previous version we achieved it in below way,

$query = <<<SQL
SELECT *
FROM `table`
WHERE `column` = true;
SQL;

But now you can follow the below way,

$query = <<<SQL
SELECT *
FROM `table`
WHERE `column` = true;
SQL;

These update changes are

  • To enable the closing marker for indenting
  • To remove the new line requirement after the closing marker

Argon2 Password Hash Enhancements

In old PHP, we got Argon2 Password hashing which was a modern algorithm to secure passwords using hashes. Here in latest version we have 3 different types Password hashing mechanism ie.,

  • Argon2i
  • Argon2d
  • Argon 2id.

 

password_hash():

Argon2id is now the recommended Argon2 variant to use in pasword_* functions.

Password_argon2i   
password_hash('password', PASSWORD_ARGON2ID, ['memory_cost' => 1<<17, 'time_cost' => 4, 'threads' => 2]);
password_verify();
The password_verify() method will works with Argon2id in the addition to Argon2i.

 

password_needs_rehash();

This function will also accept Argon2id hashes and if any cost factors change, this will return true.

$hash = password_hash('password', PASSWORD_ARGON2ID);
password_needs_rehash($hash, PASSWORD_ARGON2ID); // false
password_needs_rehash($hash, PASSWORD_ARGON2ID, ['memory_cost' => 1<<17]);

 

Deprecate and Remove image2wbmp()

This function returns the bitmap or WBMP image format. This method imagewbmp() is also used for doing the monochrome conversion. To overcome the duplication, we can use image2wbmp() to deprecate and don’t need to use the imagewbmp() anymore.

Deprecate and Remove Case-Insensitive Constants

In current situation we need to use both case-insensitive constants and case-sensitive. It will be quite complex to use case-insensitive constants. To reduce this complexities, PHP 7.3 proposing to deprecate case-insensitive constants.
Current features we have are,

  • Constants declared with define() are case-sensitive by default.
  • Class constants are case-sensitive.
  • It is possible to declare case-insensitive constants by passing true as the third parameter of define().
  • Global constants declared with const are always case-sensitive. We need to check a point that, this applies only to the short name of the constant, while namespaces in PHP are always case-insensitive.

For, the PHP 7.3 proposed to depreciate to remove these items:

  • Deprecate calling define() with third parameter is always true.
  • Deprecate accessing a case-insensitive constant with a casing that is different from the declaration-site. So the constants null ,false , and true are exempt from this.

Same Site Cookie

PHP 7.3 introducing us to add same site flag for cookies, this feature will have an impact on four core functions.

  • session_set_cookie_params
  • setcookie
  • session_get_cookie_params
  • setrawcookie

This process of moving all the cookie option can be achieved in two ways, either by adding the array or by adding array of options or new argument.
Either way it will work,

bool setcookie(
  string $name
  [, string $value = ""
  [, int $expire = 0
  [, string $path = ""
  [, string $domain = ""
  [, bool $secure = false
  [, bool $httponly = false ]]]]]]
)

 

bool setcookie (
  string $name
  [, string $value = ""
  [, int $expire = 0
  [, array $options ]]]
)

 

Best To Read: Best Laravel Security Practices You Must Try It Out!

So far we have revised all the new updates and features of PHP 7.3 and hope it helps you! also you can expect more about PHP features, updates, tips and tricks in coming blogs.

Harikrishnan R

Around 3 years of experience he scored intense knowledge on PHP, Laravel, Symfony, Angular & ensuring to learn the new & best methods to bring excellence in building applications. Also he has some aspiring dream to do Doctorate and the strange reason behind this will definitely leave a smile on your face! Yeah because he just loves writing his name as Dr. Harikrishnan