Scalar Type Declarations
Function parameter type declarations in PHP 7 can now be scalar types. In PHP 5, only class names, interfaces, array, or callable (since PHP 5.4, i.e., functions, including anonymous functions) were allowed. Now string, int, float, and bool can also be used.
<?php
// 强制模式
function sumOfInts(int ...$ints)
{
return array_sum($ints);
}
var_dump(sumOfInts(2, '3', 4.1));
The above example will output:
int(9)
Note that the strict mode issue mentioned above also applies here: in coercive mode (the default, i.e., forced type conversion), parameters that do not meet expectations are still coerced; in strict mode, a fatal TypeError is triggered.
Return Type Declarations
PHP 7 adds support for return type declarations. Similar to parameter type declarations, return type declarations specify the type of a function's return value. The available types are the same as those available in parameter declarations.
<?php
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
The above example will output:
Array
(
[0] => 6
[1] => 15
[2] => 24
)
NULL Coalescing Operator
Since there are many cases where ternary expressions and isset() are used together in everyday code, the NULL coalescing operator returns the variable's own value if it exists and is not NULL; otherwise, it returns its second operand.
The example is as follows:
<?php // 如果 $_GET['user'] 不存在返回 'nobody',否则返回 $_GET['user'] 的值 $username = $_GET['user'] ?? 'nobody'; // 类似的三元运算符 $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; ?>
Spaceship Operator (Combined Comparison Operator)
The spaceship operator is used to compare two expressions. It returns -1, 0, or 1 when $a is greater than, equal to, or less than $b, respectively.
The example is as follows:
<?php // 整型 echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // 浮点型 echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // 字符串 echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ?>
Constant Arrays using define()
The example is as follows:
<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // 输出 "cat"
?>
Anonymous Classes
It is now supported to instantiate an anonymous class using new class. The example is as follows:
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
echo $msg;
}
});
var_dump($app->getLogger());
?>
The above example will output:
object(class@anonymous)#2 (0) {
}
Unicode Codepoint Escape Syntax
It accepts a Unicode codepoint in hexadecimal form and prints a string in UTF-8 encoding enclosed by double quotes or heredoc. Any valid codepoint is accepted, and leading zeros may be omitted.
echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";
The above example will output:
ª ª (same as before but with optional leading 0's) 香
Closure::call()
Closure::call() now has better performance, allowing a closure to be temporarily bound to an object and called succinctly.
<?php
class A {private $x = 1;}
// Pre PHP 7 代码
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX();
// PHP 7+ 代码
$getX = function() {return $this->x;};
echo $getX->call(new A);
The above example will output:
1 1
Filtering for unserialize()
This feature aims to provide a safer way to unpack unreliable data. It prevents potential code injection through a whitelist approach.
<?php // 转换对象为 __PHP_Incomplete_Class 对象 $data = unserialize($foo, ["allowed_classes" => false]); // 转换对象为 __PHP_Incomplete_Class 对象,除了 MyClass 和 MyClass2 $data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]); // 默认接受所有类 $data = unserialize($foo, ["allowed_classes" => true]);
IntlChar
The newly added IntlChar class aims to expose more ICU functionality. This class defines many static methods for manipulating Unicode characters in multiple character sets.
<?php
printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));
The above example will output:
10ffff COMMERCIAL AT bool(true)
To use this class, please install the Intl extension first.
Expectations
Expectations is a backward-compatible way to enhance the previous assert(). It makes enabling assertions in production environments zero-cost, and provides the ability to throw specific exceptions when assertions fail.
<?php
ini_set('assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError('Some error message'));
?>
The above example will output:
Fatal error: Uncaught CustomError: Some error message
use Enhancement
Classes, functions, and constants imported from the same namespace can now be imported at once using a single use statement.
<?php
// PHP 7 之前版本用法
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP 7+ 用法
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>
Generator Enhancement
The functionality of Generator has been enhanced, which can implement many advanced features.
<?php
<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}
function gen2()
{
yield 3;
yield 4;
}
foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
?>
The above example will output:
1 2 3 4
Integer Division
A new integer division function intdiv() has been added. Usage example:
<?php var_dump(intdiv(10, 3)); ?>
The above example will output:
int(3)
For more information, please refer to:http://www.example.com/php/php7-new-features.html。