新增操作符
1、??
$username = $_GET['user'] ?? '';
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
2、<=>
$number1 <=> $number2; 当 $number1 小于、等于、大于 $number2 时 分别返回 -1,0,1
新增函数
intdiv(被除数, 除数) — 对除法结果取整
intdiv(3, 2) //1
define 可以定义数组
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
返回类型声明
function test() :int
{
return 1; //true
return '1'; //true
return 'string'; //false
}
标量类型声明
function test(string $name) :int
{
return 22;
}
string integer float boolean
可以捕获核心错误
Error层次结构
Throwable
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
Exception
核心排序的优化
php5: array(1=>0, 0=>0) //快速排序(非稳定排序)
php7: array(0=>0, 1=>0) //快速排序+选择排序(稳定排序)
比php5多了个抽象语法数(abstract snytax tree) AST
PHP -> Parser -> AST ->Opcodes -> Execution
性能增加了,内存消耗也在增加但可以忽略不计
匿名类 可以通过new class实例化一个匿名类
function getAnonymousClass($config) {
return new class($config) {};
}
暂时绑定一个方法到对象上并调用
$f = function() {
p($this->name);
};
class F {
private $name = 'F';
}
$f->call(new F);
统一的语法变量
括号不影响行为 从左至右
$a = 'b';
$b = ['1', '2', '3'];
var_dump($$a[1]);
var_dump(($$a)[1]);
php5:
Notice: Uninitialized string offset: 1 in E:\Program Files\phpStudy\WWW\test.php on line 4
Notice: Undefined variable: in E:\Program Files\phpStudy\WWW\test.php on line 4
NULL
Parse error: syntax error, unexpected '[' in E:\Program Files\phpStudy\WWW\test.php on line 4
php7: string(1) "2" string(1) "2"
Expression PHP5 PHP7
$$foo['bar']['baz'] ${$foo['bar']['baz']} ($$foo)['bar']['baz']
$foo->$bar['baz'] $foo->{$bar['baz']} ($foo->$bar)['baz']
$foo->$bar['baz']() $foo->{$bar['baz']}() ($foo->$bar)['baz']()
Foo::$bar['baz']() Foo::{$bar['baz']}() (Foo::$bar)['baz']()
关于命名空间
// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
list 的修改
1、
list($array[], $array[], $array[]) = [1, 2, 3];
var_dump($array);
php5: array(3) { [0]=> int(3) [1]=> int(2) [2]=> int(1) }
php7: array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
2、不允许赋空值
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
php7会报错 Fatal error: Cannot use empty list
3、不再支持字符串拆分
$string = "xy";
list($x, $y) = $string;
var_dump($x, $y);
php5: string(1) "x" string(1) "y"
php7: null null
foreach 的修改
变量引用,会影响对数组的循环
$array = [0];
foreach ($array as &$val) {
var_dump($val);
$array[1] = 1;
}
php5:int(0)
php7: int(0) int(1)