PHP 7 is the next major version of the PHP language. You really should check it out and upgrade.
Choosing the version 7 (instead of 6) was chosen because a lot of existing books were mentioning PHP 6 long before the development of the next major version after PHP 5 started. Andi Gutmans said “We’re going to skip version 6 because years ago, we had plans for a 6 but those plans were very different from what we’re doing now,” so the name PHP 7 was chosen.
Most important changes from PHP 5:
Be sure to read more about the changes in the migration chapter of PHP manual.
Thanks to AST (Abstract Syntax Tree) implemented in PHP7 now you can write expressions in the more predictable ways.
$obj->someMethod()()()()();
$var = 'Hello World!';
echo (is_string($var) ? 'strlen' : 'count')($var);
echo [new ArrayObject($_SERVER), 'count']();
With uniform variable syntax, you can now do more operations on expressions.
In previous versions you couldn’t catch fatal errors. Now you can do this:
<?php
function doSomething($obj)
{
$obj->nope();
}
try {
doSomething(null)
} catch (\Error $e) {
echo "Error: {$e->getMessage()}\n";
}
// Error: Call to a member function method() on a non-object
Now you can enforce parameter types as strings (string), integers (int), floating-point numbers (float), and booleans (bool). Type declarations (previously known as type hints) in PHP 5 were class names, interfaces, array and callable.
<?php
// Coercive mode
function sum (int ...$numbers)
{
return array_sum($numbers);
}
var_dump(sum(2, '3', 4.1)); // outputs 9
Besides coercive mode there is also strict mode which can be enabled per file basis with:
<?php
declare(strict_types=1);
Read more about type declarations in the PHP manual.
The spaceship operator is used for three-way comparison of two expressions. It returns:
Example of spaceship operator where you need to sort multidimensional array
To do this, you can use usort()
with comparison function:
<?php
$items = [
['title' => 'Mouse'],
['title' => 'Computer'],
['title' => 'LCD Screen'],
];
// sort items by title
usort($items, function ($a, $b) {
return $a['title'] <=> $b['title'];
});
PHP 7 has two new functions random_bytes()
and random_int()
for generating
cryptographically secure integers and strings in a cross platform way.
Before PHP 7 you had to use the generator on the platform. For example, CryptGenRandom on Windows and /dev/urandom on Linux. If you’re building modules that must work on all platforms, this might be an issue. In PHP 7 you can simply use the built-in generator.
It turned out that often you needed to use ternary operator with isset()
function.
An example where you need to check if the GET data has been sent and set the
$username
based on that. In PHP 5 you could do something like this:
<?php
$user = isset($_GET['user']) ? $_GET['user'] : 'Guest';
Now you can simplify this a lot:
<?php
$user = $_GET['user'] ?? 'Guest';
Other resources and tutorials to get to know and use PHP 7: