假如现在我们有这样的需求,要对php源文件就行语法检测,实现编码规范。php5之前的话,没有AST,直接从parser就生成了opcodes!就需要借助一些外部的php语法解析器来实现;而php7增加了AST,我们可以自己去实现这样一个扩展,利用扩展提供的函数可以直接获取文件对应的的AST结构,而这样的结构正是我们可以识别的,所以就可以在这个基础上去做一些优化和判断了。
64位的INT支持
支持存储大于2GB的字符串
支持上传大小大于2GB的文件
保证字符串在所有平台上【64位】都是64bit
统一的语法变量
$$foo[‘bar’][‘baz’]
//PHP5
($$foo)[‘bar’][‘baz’]
//PHP7: 遵循从左到右的原则
${$foo[‘bar’][‘baz’]}
foreach循环的改进
//PHP5
$a = array(1, 2, 3);foreach ($a as $v){var_dump(current($a));}
int(2)
int(2)
int(2)
$a = array(1, 2, 3);$b=&$a;foreach ($a as $v){var_dump(current($a));}
int(2)
int(3)
bool(false)
$a = array(1, 2, 3);$b=$a;foreach ($a as $v){var_dump(current($a));}
int(1)
int(1)
int(1)
//PHP7:不再操作数据的内部指针了
$a = array(1, 2, 3);foreach ($a as $v){var_dump(current($a))}
int(1)
int(1)
int(1)
$a = array(1, 2, 3);$b=&$a;foreach ($a as $v){var_dump(current($a))
int(1)
int(1)
int(1)
$a = array(1, 2, 3);$b=$a;foreach ($a as $v){var_dump(current($a))}
int(1)
int(1)
int(1)
新增的几个操作符
//<=> – 比较两个数的大小【-1:前者小于后者,0:前者等于后者,1:前者大于后者】
echo 1 <=> 2;//-1
echo 1 <=> 1;//0
echo 1 <=> 0;//1
// ** – 【a的b次方】
echo 2 ** 3;//8
//?? – 三元运算符的改进
//php5
$_GET[‘name’] ? $_GET[‘name’] : ”;//Notice: Undefined index: …
//php7
$_GET[‘name’] ?? ” -> ”;
//\u{xxxx} – Unicode字符的解析
echo “\u{4f60}”;//你
echo “\u{65b0}”;//新
返回类型的声明
function getInt() : int {
return “test”;
};
getInt();
//PHP5
#PHP Parse error: parse error, expecting ‘{‘…
//PHP7
#Fatal error:Uncaught TypeError: Return value of getInt() must be of the type integer, string returned
标量类型的声明
function getInt(int $num) : int {
return $num;
};
getInt(“test”);
//PHP5
#PHP Catchable fatal error: Argument 1 passed to getInt() must be an instance of int, string given…
//PHP7
#Fatal error: Uncaught TypeError: Argument 1 passed to getInt() must be of the type integer, string given…
核心错误可以通过异常捕获了
try {
non_exists_func();
} catch(EngineException $e) {
echo “Exception: {$e->getMessage();}\n”;
}
//这里用php7试了一下还是没法捕获,但是看鸟哥介绍说是可行的。。。
#Exception: Call to undefined function non_exists_func()
上下问敏感的词法分析
//PHP5
class Collection {public function foreach($arr) {}}
#Parse error: parse error, expecting `”identifier (T_STRING)”’…
//PHP7
class Collection {
public function foreach($arr) {}
public function in($arr){}
public function where($condition){}
public function order($condition){}
}
$collection = new Collection();
$collection->where()->in()->foreach()->order();