PHP7带来的新东西
类型声明
PHP7
中的函数(包括类的方法)形参支持标量类型声明,在此之前只支持类名、接口、数组、callable
类型,现在可以使用 int
、 string
、 float
、 bool
类型
PHP7
增加了对返回值类型声明的支持,可用的类型与参数声明中的类型相同
function add(int $a, int $b): int {
return $a+$b;
}
echo add(1, 2);//3
echo add(1.5, 2.6);//报错
NULL合并运算符 ??
返回从左向右,第一个存在且不为 NULL
的操作数的值,如果都没有定义,则返回 NULL
结合比较运算符(太空船操作符) <=>
当左边小于、等于、大于右边,分别返回-1,0,1
通过 define
定义常量数组
define('NAME', ['a', 'b']);
错误处理
PHP7
改变了大多数错误处理的方式,把 E_ERROR
和 E_PARSE
类型的错误作为 Error
异常抛出,Error
和 Exception
都继承自 Throwable
匿名函数(闭包函数)
$a = function(){
echo 'b';
}
$a();
通过 new class
实例化一个匿名类
<?php
$a = new class{
public function b()
{
echo 'c';
}
};
$a->b();//输出c
支持 unicode codepoint
语法表示的字符
echo "\u{9999}";
use
加强
从同一个 namespace
导入的类、函数、常量可以通过单个 use
一次性导入
//PHP7之前的语法
use a\b\c;
use a\b\d;
//PHP7之后的语法
use a\b\{c, d AS e}
整除函数 intdiv
<?php
echo intdiv(9,3),PHP_EOL;//3
echo intdiv(10,3),PHP_EOL;//3
echo intdiv(5,10),PHP_EOL;//0
Session选项
PHP7
为 session_start
函数增加了 options
参数,可以动态传入 session
配置项
PHP7带来的变更
字符串处理机制修改
含有十六进制字符的字符串不再视为数字, 也不再区别对待。
<?php
var_dump("0x123" == "291"); // false
var_dump(is_numeric("0x123")); // false
var_dump(is_numeric(0x123)); // true
整型处理机制修改
Int64
支持, 统一不同平台下的整型长度, 字符串和文件上传都支持大于2GB. 64位 PHP7
字符串长度可以超过 2^31
次方字节.
参数处理机制修改
重复参数命名不再支持,以下代码报错
public function foo($a, $b, $unused, $unused) {
// ...
}
func_get_arg()
和func_get_args()
这两个方法返回参数当前的值, 而不是传入时的值, 当前的值有可能会被修改function foo($x) {
$x++;
echo func_get_arg(0);
}
foo(1); //返回2
foreach处理机制修改
foreach
循环不再影响数组内部指针$arr = [1,2,3];
foreach ($arr as &$val) {
var_dump(current($arr));// php7 全返回1
}
list 处理机制修改
不再按照相反的顺序赋值
//$arr将会是[1,2,3]而不是之前的[3,2,1]
list($arr[], $arr[], $arr[]) = [1,2,3];
var_dump($arr);
不再支持字符串拆分功能
// $x = null 并且 $y = null
$str = 'xy';
list($x, $y) = $str;
变量处理机制修改
对变量、属性和方法的间接调用现在将严格遵循从左到右的顺序来解析,而不是之前的混杂着几个特殊案例的情况。 下面这张表说明了这个解析顺序的变化
PHP7带来的废弃
废弃的扩展
POSIX
正则表达式扩展(erge
系列正则表达式函数)
从PHP5.3
起,erge
系列函数已经不建议使用了,使用preg
替代mssql 扩展
使用sqlsrv
或者pdo_sqlsrv
替代mysql 扩展
使用mysqli
或者pdo_mysql
替代sybase 扩展
使用sybase_ct
替代
废弃的特性
同名的类方法不再作为类的构造函数
实例方法不能用静态方法的方式调用
废弃的函数
方法调用
call_user_method()
call_user_method_array()
应该采用
call_user_func()
和call_user_func_array()
加密相关函数
mcrypt_generic_end()
mcrypt_ecb()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_ofb()
PHP7.1
以后mcrypt_*
序列函数都将被移除。推荐使用:openssl
序列函数杂项
set_magic_quotes_runtime
set_socket_blocking
split()
imagepsbbox()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
废弃的用法
$HTTP_RAW_POST_DATA
变量被移除, 使用php://input
来代ini
文件里面不再支持#
开头的注释, 使用;
移除了
ASP
格式的支持和脚本语法的支持:<%
和<script language=php >
PHP7带来的好处
性能上的大幅度提升