Date post: | 17-Aug-2015 |
Category: |
Software |
Upload: | mark-baker |
View: | 529 times |
Download: | 5 times |
Flying Under the Radar
The new features of PHP 7 that you probably haven’t heard about
PHP 7
• Due for release in November 2015
• Major new Features/Enhancements• Speed, particularly working with objects
• Scalar Type Hinting
• Return Type Hinting
• Abstract Syntax Tree
PHP 7 – Spaceship Operator (<=>)
• Officially called the Combined Comparison Operator
• Useful for comparison callbacks, e.g. usort()
$x = $a <=> $b;
Returns -1 if $a < $b
Returns 0 if $a == $b
Returns 1 if $a > $b
PHP 7 – Null Coalescence Operator (??)
• Variant of the Ternary Operator (?:)
• Useful for setting default values (eg. for undefined variables)
// PHP 5
$value = isset($value) ? $value : 'default';
// PHP 7
$value = $value ?? 'default';
PHP 7 – Unicode Codepoint Escape Syntax
• Allows direct injection of Unicode codepoints in text strings
echo "ma\u{00F1}ana"; // outputs mañana
echo "man\u{0303}ana"; // outputs mañana
"n" with combining "~" character (Codepoint U+0303)
echo "\u{1F602}"; // outputs 😂
echo "\u{202E}Reversed text"; // outputs txet desreveR
Using Codepoint U+202E, RIGHT-TO-LEFT OVERRIDE
PHP 7 – Array Constants
• PHP 5.6 allowed constant definitions to contain basic operators
• PHP 7 has added support, allowing constant definitions to include arrays
define('ANIMALS', ['dog', 'cat', 'rabbit', 'aardvark']);
echo ANIMALS[1]; // outputs cat
• Class constants have allowed this since PHP 5.6.0
PHP 7 – Generator Delegation
• Simplifies “nested” Generators
• Simplifies the return of individual elements from any Iterable
// PHP 5.5
foreach(range(1, 5) as $value) {
yield $value
}
// PHP 7
yield from range(1, 5);
PHP 7 – Anonymous Classes
• Allow you to create a dynamic class instance, complete with properties and methods
$instance = new class('Hello World') {
private $data;
public function __construct($data) {
$this->data = $data;
}
public function reverse() {
echo strrev($this->data);
}
};
$instance->reverse(); // outputs dlroW olleH
PHP 7