php - 在 PHP7 中使用匿名类的好例子是什么

标签 php php-7 anonymous-class

当我寻找新的 PHP7-features我偶然发现了匿名类。

我不明白它们什么时候应该有用,所以找了一个例子。

我读了this article ,但我看不到此功能的好处。

在结论之前的最后一节中,他们写了以下关于优点的内容:

One advantage is that we no longer need the named extension. Normally the named extension would be hidden away in some included file, if you ever needed to see how it is defined you have to start searching for it. With anonymous classes the definition is in the same place the object is created.

另一方面,我看到了一个很大的缺点,因为你只能在定义它的地方使用这个匿名类。

有人可以解释一下这个功能什么时候有用吗?

特别是如果它可以帮助构建自定义系统或扩展像 WordPress 这样的 CMS(最好是德语,但也欢迎使用英语)。

最佳答案

匿名类在为监听器接口(interface)编写实现类时可能很有用,因此您无需创建文件或泛型类来实现一次。

One of the most elegant things about anonymous classes is that they allow you to define a one-shot class exactly where it is needed. In addition, anonymous classes have a succinct syntax that reduces clutter in your code. Java in a nutshell

因此,您可以拥有接口(interface)的匿名实现,甚至可以使用附加属性或重写方法扩展类。

例子:

return new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }
};

另一种情况:

提供适配器类的简单实现。适配器类是定义由其他某个对象调用的代码的类。以名为 File 的类中的 list() 方法为例。此方法列出目录中的文件。不过,在返回列表之前,它会将每个文件的名称传递给您必须提供的 FilenameFilter 对象。此 FilenameFilter 对象接受或拒绝每个文件。当您实现 FilenameFilter 接口(interface)时,您正在定义一个适配器类以与 $file->list() 方法一起使用。由于此类的主体通常很短,因此很容易将适配器类定义为匿名类。

$file = new File("/src");

// Now call the list() method with a single FilenameFilter argument
// Define and instantiate an anonymous implementation of FilenameFilter
// as part of the method invocation expression. 
$filelist = $file->list(new class extends FilenameFilterClass {
  public function accept(File $f, string $otherInfo) { 
    return pathinfo($f, PATHINFO_EXTENSION) === ".php"; 
  }
});

关于匿名类的一些很好的基本理解和使用可以在 Java 上找到(我知道它不是 PHP ,但它有助于理解)示例在 https://www.geeksforgeeks.org/anonymous-inner-class-java/

关于php - 在 PHP7 中使用匿名类的好例子是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941191/

相关文章:

php - 使用 Smarty 或 Backbone.js 制作 javascript 模板

php - 传递给 Y 的参数 X 必须是 bool 值的实例, bool 值给定 - PHP7

php - Magento 2 CSS 无法加载

java - 泛型类作为参数

php - 如何在 php(或 codeigniter)中区分 ajax 调用和浏览器请求?

php - 如何设置和输出php的缓冲区内容

php - 如何使用 php 更新 mysql 的当前日期?

php - PDO数据库用户存在控制

java - Kotlin 对象表达式 : Comparator example

php - PHP 7 中的匿名类