匿名类 (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中文网其他相关文章!