PHP7: twice as fast, half the memory consumption and… Spaceships!
PHP 7 is out and comes with a lot of improvements, new features and a new version of the Zend Engine. I got your attention probably by mentioning spaceships in the title. So let’s start off with this new feature PHP7 brings us, the Spaceship Operator.
Because having a spaceship is one thing, operating it is another 😉
The Spaceship Operator
Known in mathematics and other programming languages as the sign or Sgn function, spaceship operators are used to compare two expressions. Returning 1
when the first is greater than the second, 0
when both are equal and -1
when the first is less than the second.
// Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1
Null coalesce operator
I’m a big fan of the ternary operator – when used wisely! They greatly improve the readability of simple checks and assignments of variables.
Now a common use case is simplified by the Null calesce operator, checking if a variable "isset". You can even chain them.
// Fetches the value of $_GET['user'] and returns 'nobody' // if it does not exist. $username = $_GET['user'] ?? 'nobody'; // This is equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // Coalesces can be chained: this will return the first // defined value out of $_GET['user'], $_POST['user'], and // 'nobody'. $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
More new features
Other new features include:
- Scalar type declarations
- Return type declarations
- Constant arrays using define()
- Anonymous classes
- Unicode codepoint escape syntax
- Closure::call()
- Filtered unserialize()
- IntlChar
- Expectations
- Group use declarations
- Generator Return Expressions
- Generator delegation
- Integer division with intdiv()
- Session options
- preg_replace_callback_array()
- CSPRNG Functions
- list() can always unpack objects implementing ArrayAccess
Read more about them at php.net.
PHP7 Performance
Zend made a nice infographic of PHP7’s performance improvement benchmark results, which are quite impressive: