匿名類別 (PHP 7)
#現在支援透過new class 來實例化一個匿名類,這可以用來取代一些「用後即焚」的完整類別定義。
<?php 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()); ?>
以上程式會輸出:
object(class@anonymous)#2 (0) {
}
Closure::call() (PHP 7)
Closure::call() 現在有著更好的效能,簡短幹練的暫時綁定一個方法到物件上閉包並呼叫它。
<?php class A {private $x = 1;} // Pre PHP 7 code $getXCB = function() {return $this->x;}; $getX = $getXCB->bindTo(new A, 'A'); // intermediate closure echo $getX(); // PHP 7+ code $getX = function() {return $this->x;}; echo $getX->call(new A);
以上例程會輸出:
1
1
#為unserialize()提供篩選(PHP 7)
這個特性旨在提供更安全的方式解包不可靠的資料。它透過白名單的方式來防止潛在的程式碼注入。
<?php // converts all objects into PHP_Incomplete_Class object $data = unserialize($foo, ["allowed_classes" => false]); // converts all objects into PHP_Incomplete_Class object except those of MyClass and MyClass2 $data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]); // default behaviour (same as omitting the second argument) that accepts all classes $data = unserialize($foo, ["allowed_classes" => true]);
Group use declarations (PHP 7)
從相同namespace 匯入的類別、函數和常數現在可以透過單一use語句一次性導入了。
<?php // 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}; ?>
以上是php7匿名類,導入類別和閉包使用等新特性介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!