php7新特性

给自己制定了一套学习计划,趁着空余的时间恶补下知识。
补充为主,革新为辅。

本文从php7官方文档过滤,记录一些常用的操作的变化。
原文请看:http://php.net/manual/zh/migration70.incompatible.php

变量、属性和方法 从左到右解析

例如 $foo->$bar[‘baz’]()

在php5中的解析顺序为 $foo->{$bar[‘baz’]}(),在php7中如果不遵循这个规则,则需要使用 圆括号包裹优先解析的内容,保证解析过程不出错。则为 ($foo->$bar)[‘baz’]()

list() 将以正向的顺序来进行赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

//Output of the above example in PHP 5:

array(3) {
[0]=>
int(3)
[1]=>
int(2)
[2]=>
int(1)
}

//Output of the above example in PHP 7:

array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}

foreach通过引用遍历时,有更好的迭代特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
?>

//Output of the above example in PHP 5:
int(0)

//Output of the above example in PHP 7:
int(0)
int(1)

在迭代过程中,动态增加数组的长度foreach将会继续执行。

十六进制字符串不再被认为是数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

//Output of the above example in PHP 5:
bool(true)
bool(true)
int(15)
string(2) "oo"

//Output of the above example in PHP 7:
bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

//可以通过 filter_var() 来检测变量是否包含16进制数字,并转换为int型数字
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
var_dump($int); // int(65535)

\u{ 可能引起错误

由于新的 Unicode codepoint escape syntax语法, 紧连着包含\u{ 的字串可能引起致命错误,应该避免反斜杠开头。

不要使用下列的名字来命名 类、接口以及 trait

resource object mixed numeric
虽然在 PHP 7.0 中, 这并不会引发错误, 但是这些名字是保留给将来使用的。

移除了 ASP 和 script PHP 标签

1
2
3
<% %>
<%= %>
<script language="php"></script>

在函数中检视参数值会返回 当前 的值

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
function foo($x) {
$x++;
var_dump(func_get_arg(0));
}
foo(1);
?>

//Output of the above example in PHP 5:
1

//Output of the above example in PHP 7:
2

$HTTP_RAW_POST_DATA 被移除 请使用 php://input 作为替代

INI 文件中 注释由 # 变为 ; (分号)

JSON 扩展已经被 JSOND 取代

  1. 数值不能以点号(.)结束 (例如,数值 34. 必须写作 34.0 或 34)
  2. 如果使用科学计数法表示数值,e 前面必须不是点号(.) (例如,3.e3 必须写作 3.0e3 或 3e3)
  3. 空字符串不再被视作有效的 JSON 字符串。

本文仅罗列php7部分重要的 常用的变化,如果有兴趣的小伙伴们建议点击文章头部的原文链接仔细阅读更新之后的变化,希望我的这篇文章不会误人子弟。


评论区