1. Operator NULL merge operator)
I put this first because I find it useful. Usage:
$a = $_GET['a'] ?? 1;
It is equivalent to:
We know that the ternary operator can be used like this:
$a ?: 1
But this is based on the premise that $a has been defined. The new ?? operator can simplify judgment.
2. Function return value type declaration
The examples provided by the official documentation note that the side length parameter syntax of ... is only available in PHP 5.6 and above):
<span><span><php </span></span>
It can be seen from this example that now functions (including anonymous functions) can specify the type of return value.
The way this statement is written is somewhat similar to swift:
<span><span>func sayHello(personName: String) -> String { </span></span>
This feature can help us avoid some problems caused by PHP's implicit type conversion. Thinking about the expected results before defining a function can avoid unnecessary mistakes.
However, there is also a feature that needs attention here. PHP 7 adds a declare directive: strict_types, which uses strict mode.
When using return value type declaration, if it is not declared in strict mode, if the return value is not of the expected type, PHP will still cast it. But if it is strict mode, a Fatal error of TypeError will be triggered.
Forced mode:
<span><span><php </span></span>
The above code executes normally and the foo function returns int 1 without any errors.
Strict mode:
<span><span><php </span></span>
在声明之后,就会触发致命错误。
是不是有点类似与 js 的 strict mode?
3. 标量类型声明
PHP 7 中的函数的形参类型声明可以是标量了。在 PHP 5 中只能是类名、接口、array 或者 callable (PHP 5.4,即可以是函数,包括匿名函数),现在也可以使用 string、int、float和 bool 了。
官方示例:
<span><span><php </span></span>
需要注意的是上文提到的严格模式的问题在这里同样适用:强制模式默认,既强制类型转换)下还是会对不符合预期的参数进行强制类型转换,严格模式下则触发 TypeError 的致命错误。
4. use 批量声明
PHP 7 中 use 可以在一句话中声明多个类或函数或 const 了:
<span><span><php </span></span>
但还是要写出每个类或函数或 const 的名称并没有像 python 一样的 from some import * 的方法)。
需要留意的问题是:如果你使用的是基于 composer 和 PSR-4 的框架,这种写法是否能成功的加载类文件?其实是可以的,composer 注册的自动加载方法是在类被调用的时候根据类的命名空间去查找位置,这种写法对其没有影响。
5. 其他的特性
其他的一些特性我就不一一介绍了,有兴趣可以查看官方文档:http://php.net/manual/en/migration70.new-features.php
简要说几个:
PHP 5.3 开始有了匿名函数,现在又有了匿名类了;
define 现在可以定义常量数组;
闭包 Closure)增加了一个 call 方法;
生成器或者叫迭代器更合适)可以有一个最终返回值return),也可以通过 yield from 的新语法进入一个另外一个生成器中生成器委托)。
生成器的两个新特性return 和 yield from)可以组合。具体的表象大家可以自行测试。PHP 7 现在已经到 RC5 了,最终的版本应该会很快到来。