[TOC] ## 开关严格模式 通过指定`strict_types`的值(1 或者 0),1 表示严格类型校验模式;0 表示弱类型校验模式 ``` declare(strict_types=1); function func($num):int{ return $num; } var_dump(func(2.5)); // 报异常 ``` ``` function func($num):int{ return $num; } var_dump(func(2.5)); //2 对类型强制转换 ``` ``` declare(strict_types=0); function func($num):int{ return $num; } var_dump(func(2.5));//2 对类型强制转换 ``` ## NULL 合并运算符 新增?? 同 ?: ``` //$a="1"; echo $a??"2"; // 2 ``` ## 太空船操作符(组合比较符) 当$a大于、等于或小于$b时它分别返回-1、0或1 ``` // 整型 echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // 浮点型 echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // 字符串 echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ``` ## define() 定义常量数组 ``` define("DEMO", ['a', 'b', 'c']); echo DEMO[0];//a ``` ## 匿名类 ``` interface Logger{ public function log(string $msg); } class Appliction{ private $logger; public function getLogger():Logger{ return $this->logger; } public function setLogger(Logger $logger){ $this->logger=$logger; } } $app = new Appliction(); $app->setLogger(new class implements Logger{ public function log(string $msg){ echo $msg; } }); $app->getLogger()->log("hello word"); ``` ## Closure::call() 类js的 call ``` class A {private $x = 1;} // Pre PHP 7 代码 $getXCB = function() {return $this->x;}; $getX = $getXCB->bindTo(new A, 'A'); // intermediate closure echo $getX(); // PHP 7+ 代码 $getX = function() {return $this->x;}; echo $getX->call(new A); ``` ## use 加强 ``` // PHP 7 之前版本用法 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+ 用法 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}; ```