问题描述
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 = [
\App\Console\Commands\Inspire::class,
];
推荐答案
此功能已在PHP 5.5中实现.
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 \App\Console\Commands\Inspire;
//...
protected $commands = [
Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];
更新:
此功能对于 后期静态绑定也很有用 .
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
这篇关于什么是:: class在PHP中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!