PHP 中的 ::class 是什么? [英] What is ::class in PHP?

查看:26
本文介绍了PHP 中的 ::class 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 中的 ::class 符号是什么?

What is the ::class notation in PHP?

由于语法的性质,快速的 Google 搜索不会返回任何结果.

A quick Google search returns nothing because of the nature of the syntax.

冒号类

使用这种表示法有什么好处?

What's the advantage of using this notation?

protected $commands = [
    AppConsoleCommandsInspire::class,
];

推荐答案

SomeClass::class 将返回 SomeClass 的完全限定名称,包括命名空间.此功能已在 PHP 5.5 中实现.

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5.

文档:http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name

它非常有用有两个原因.

It's very useful for 2 reasons.

  • 您不必再将类名存储在字符串中.因此,当您重构代码时,许多 IDE 可以检索这些类名
  • 您可以使用 use 关键字来解析您的类,而无需编写完整的类名.
  • You don't have to store your class names in strings anymore. So, many IDEs can retrieve these class names when you refactor your code
  • You can use the use keyword to resolve your class and you don't need to write the full class name.

例如:

use AppConsoleCommandsInspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "AppConsoleCommandsInspire"
];

更新:

这个特性对于后期静态绑定也很有用.

This feature is also useful for Late Static Binding.

您可以使用 static::class 特性来获取父类中派生类的名称,而不是使用 __CLASS__ 魔法常量.例如:

Instead of using the __CLASS__ magic constant, you can use the static::class feature to get the name of the derived class inside the parent class. For example:

class A {

    public function getClassName(){
        return __CLASS__;
    }

    public function getRealClassName() {
        return static::class;
    }
}

class B extends A {}

$a = new A;
$b = new B;

echo $a->getClassName();      // A
echo $a->getRealClassName();  // A
echo $b->getClassName();      // A
echo $b->getRealClassName();  // B

这篇关于PHP 中的 ::class 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆