了解了PHP7的一些特性,搭建PHP7源码编译环境,并运行官网这些新特性的代码。
在64位平台支持64位integer
在64位平台支持64位integer,长度为2^64-1 字符串。
抽象语法树
抽象语法树是语法分析之后产物,忽略了语法细节,是解释前端和后端的中间媒介。新增抽象语法树,解耦语法分析和编译,简化开发维护,并为以后新增一些特性,如添加抽象语法树编译hook,深入到语言级别实现功能。
闭包this绑定
新增Closure::call
,优化Closure::bindTo
(JavaScript中bind,apply也是一样的应用场景)。
<?php
class Foo { private $x = 3; }
$foo = new Foo;
$foobar = function () { var_dump($this->x); };
$foobar->call($foo); // prints int(3)
2-3行新建Foo的对象,第4行创建了一个foobar
的闭包,第5行调用闭包的call
方法,将闭包体中的$this
动态绑定到$foo
并执行。
同时官网上进行性能测试,Closure::call
的性能优于Closure::bindTo
。
简化isset的语法糖
从使用者角度来说,比较贴心的一个语法糖,减少了不必要的重复代码,使用情景如:
<?php
// PHP 5.5.14
$username = isset($_GET['username']) ? $_GET['username'] : 'nobody';
// PHP 7
$username = $_GET['username'] ?? 'nobody';
在服务器端想获取$_GET中的变量时,若是PHP5语法,需要使用?:
操作符,每次要重写一遍$_GET['username']
,而在PHP7就可以使用这个贴心的语法糖,省略这个重复的表达式。
yield from
允许Generator
方法代理Traversable
的对象和数组的操作。这个语法允许把yield
语句分解成更小的概念单元,正如利用分解类方法简化面向对象代码。
例子:
<?php
function g1() {
yield 2;
yield 3;
yield 4;
}
function g2() {
yield 1;
yield from g1();
yield 5;
}
$g = g2();
foreach ($g as $yielded) {
print($yielded);
}
// output:
// 12345
yield from
后能跟随Generator
,Array
,或Traversable
的对象。
匿名类
<?php
class Foo {}
$child = new class extends Foo {};
var_dump($child instanceof Foo); // true
标量类型声明
<?php
declare(strict_types=1);
function add(int $a, int $b): int {
return $a + $b;
}
var_dump(add(1, 2)); // int(3)
// floats are truncated by default
var_dump(add(1.5, 2.5)); // int(3)
//strings convert if there's a number part
var_dump(add("1", "2")); // int(3)
返回值类型声明
<?php
function get_config(): array {
return [1,2,3];
}
var_dump(get_config());
function &get_arr(array &$arr): array {
return $arr;
}
$arr = [1,2,3];
$arr1 = get_arr($arr);
$arr[] = 4;
// $arr1[] = 4;
var_dump($arr1 === $arr);
3路比较
一个语法糖,用来简化比较操作符,常应用于需要使用比较函数的排序,消除用户自己写比较函数可能出现的错误。分为3种情况,大于(1),等于(0),小于(-1)。
<?php
function order_func($a, $b) {
return $a <=> $b;
}
echo order_func(2, 2); // 0
echo order_func(3, 2); // 1
echo order_func(1, 2); // -1
导入包的缩写
<?php
import shorthand
Current use syntax:
use SymfonyComponentConsoleHelperTable;
use SymfonyComponentConsoleInputArrayInput;
use SymfonyComponentConsoleOutputNullOutput;
use SymfonyComponentConsoleQuestionQuestion;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleQuestionChoiceQuestion as Choice;
use SymfonyComponentConsoleQuestionConfirmationQuestion;
// Proposed group use syntax:
use SymfonyComponentConsole{
HelperTable,
InputArrayInput,
InputInputInterface,
OutputNullOutput,
OutputOutputInterface,
QuestionQuestion,
QuestionChoiceQuestion as Choice,
QuestionConfirmationQuestion,
};