【modernPHP專題(1)】php7概述
PHP7效能
7最大的亮點,應該就是效能提高了兩倍,某些測試環境下甚至提高到三到五倍,具體可以瞭解以下連結:
HHVM vs PHP 7 – The Competition Gets Closer!
PHP 7.0 Is Showing Very Promising Performance Over PHP 5, Closing Gap With HHVM
特性簡述
標量型別宣告
PHP 7 中的函式的形參型別宣告可以是標量了。在 PHP 5 中只能是類名、介面、array 或者 callable (PHP 5.4,即可以是函式,包括匿名函式),現在也可以使用 string、int、float和 bool 了 。
<?php // 強制模式,強制把引數int化 function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1));
強制模式(預設,既強制型別轉換)下會對不符合預期的引數進行強制型別轉換,但嚴格模式下則觸發TypeError 的致命錯誤。
嚴格模式:申明 declare(strict_types=1)即可;
返回值型別宣告
PHP 7 增加了對返回型別宣告的支援。 類似於引數型別宣告,返回型別宣告指明瞭函式返回值的型別。可用的型別與引數宣告中可用的型別相同。
<?php function arraysSum(array ...$arrays): array { # 把返回值強制轉換為string return array_map(function(array $array): string { return array_sum($array); }, $arrays); } var_dump(arraysSum([1,2,3], [4,5,6], [7,8,9])); # output array(3) { [0]=> string(1) "6" [1]=> string(2) "15" [2]=> string(2) "24" }
同樣有嚴格模式和強制模式
NULL 合併運算子
// 如果 $_GET['user'] 不存在返回 'nobody',否則返回 $_GET['user'] 的值 $username = $_GET['user'] ?? 'nobody'; // 相當於 isset($_GET['user']) ?$_GET['user'] : 'nobody'; // 類似於遮蔽notice錯誤後的: $username = $_GET['user'] ?: 'nobody';
太空船操作符(組合比較符)
用於比較兩個表示式。當$a大於、等於或小於$b時它分別返回-1、0或1。
<?php // $a 是否大於 $b , 大於就返回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() 定義常量陣列
<?php define('ANIMALS', [ 'dog', 'cat', 'bird' ]); // ANIMALS[1] = mouse; 常量數組裡面的值,是不可以更改的 echo ANIMALS[1]; // 輸出 "cat"
匿名類
現在支援通過new class 來例項化一個匿名類
interface Logger { public function log(string $msg); } class Application { private $logger; public function getLogger(): Logger { return $this->logger; } public function setLogger(Logger $logger) { $this->logger = $logger; } } $app = new Application; $app->setLogger(new class implements Logger { public function log(string $msg) { echo $msg; } }); var_dump($app->getLogger()); # output: object(class@anonymous)#2 (0) { }
為unserialize()提供過濾
這個特性旨在提供更安全的方式解包不可靠的資料。它通過白名單的方式來防止潛在的程式碼注入。
// 轉換物件為 __PHP_Incomplete_Class 物件 $data = unserialize($foo, ["allowed_classes" => false]); // 轉換物件為 __PHP_Incomplete_Class 物件,除了 MyClass 和 MyClass2 $data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]); // 預設接受所有類 $data = unserialize($foo, ["allowed_classes" => true]);
斷言assert
向後兼用並增強之前的 assert() 的方法。 它使得在生產環境中啟用斷言為零成本,並且提供當斷言失敗時丟擲特定異常的能力。
ini_set('assert.exception', 1); class CustomError extends AssertionError {} assert(2 == 1, new CustomError('Some error message'));
use 加強
從同一 namespace 匯入的類、函式和常量現在可以通過單個 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};
Generator 加強 : yield from
增強了Generator的功能,這個可以實現很多先進的特性
function gen() { yield 1; yield 2; yield from gen2(); } function gen2() { yield 3; yield 4; } foreach (gen() as $val) { echo $val, PHP_EOL; }
整除
新增了整除函式 intdiv()
var_dump(intdiv(10, 3)); # 3
array_column() 和 list()
新增支援物件陣列
list($a, $b) = (object) new ArrayObject([0, 1]);
PHP7結果:$a == 0 and $b == 1.
dirname()
增加了可選項$levels,可以用來指定目錄的層級。dirname(dirname($foo)) => dirname($foo, 2);
Closure::call()
Closure::call() 現在有著更好的效能,簡短幹練的暫時繫結一個方法到物件上閉包並呼叫它。
class A {private $x = 1;} // Pre PHP 7 程式碼 $getXCB = function() {return $this->x;}; $getX = $getXCB->bindTo(new A, 'A'); echo $getX(); //// PHP 7+ 程式碼 $getX = function() {return $this->x;}; echo $getX->call(new A);
Unicode codepoint 轉譯語法
echo "\u{aa}"; echo "\u{0000aa}"; echo "\u{9999}";
更多請參考: