Introduction to new features such as anonymous classes, imported classes and closure usage in php7

伊谢尔伦
Release: 2023-03-11 15:10:01
Original
2618 people have browsed it

匿名类 (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());
?>
Copy after login

以上例程会输出:

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, &#39;A&#39;); // intermediate closure
echo $getX();

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);
Copy after login

以上例程会输出:

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]);
Copy after login

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};
?>
Copy after login

The above is the detailed content of Introduction to new features such as anonymous classes, imported classes and closure usage in php7. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template