PHP 7 also introduced some other new features with small changes, such as new syntax for array constants, multiple default cases in switch statement, options array in session_start, and so on. Let's have a look at these too.
Starting with PHP 5.6, constant arrays can be initialized using the const keyword, as follows:
const STORES = ['en', 'fr', 'ar'];
Now, starting with PHP 7, constant arrays can be initialized using the define function, as follows:
define('STORES', ['en', 'fr', 'ar']);Prior to PHP 7, multiple default cases in a switch statement were allowed. Check out the following example:
switch(true)
{
default:
echo 'I am first one';
break;
default:
echo 'I am second one';
}Before PHP 7, the preceding code was allowed, but in PHP 7, this will result in a fatal error similar to the following:
Fatal error: Switch statements may only contain one default clause in…
Before PHP 7, whenever we needed to start a session, we just used the session_start() function. This function did not take any arguments, and all the settings defined in php.ini were used. Now, starting with PHP 7, an optional array for options can be passed, which will override the session settings in the php.ini file.
A simple example is as follows:
session_start([ 'cookie_lifetime' => 3600, 'read_and_close' => true ]);
As can be seen in the preceding example, it is possible to override the php.ini settings for a session easily.
It is common practice to serialize and unserialize objects. However, the PHP unserialize() function was not secure because it did not have any filtering options and could unserialize objects of any type. PHP 7 introduced filtering in this function. The default filtering option is to unserialize objects of all classes or types. Its basic working is as follows:
$result = unserialize($object, ['allowed_classes' => ['Packt', 'Books', 'Ebooks']]);