【发布时间】:2015-08-26 12:29:23
【问题描述】:
PHP 中的::class 表示法是什么?
由于语法的性质,快速的 Google 搜索不会返回任何内容。
冒号冒号类
使用这种表示法有什么好处?
protected $commands = [
\App\Console\Commands\Inspire::class,
];
【问题讨论】:
PHP 中的::class 表示法是什么?
由于语法的性质,快速的 Google 搜索不会返回任何内容。
冒号冒号类
使用这种表示法有什么好处?
protected $commands = [
\App\Console\Commands\Inspire::class,
];
【问题讨论】:
SomeClass::class 将返回 SomeClass 的完全限定名称,包括命名空间。此功能在 PHP 5.5 中实现。
文档:http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name
它非常有用有两个原因。
use 关键字来解析您的类,而无需编写完整的类名。例如:
use \App\Console\Commands\Inspire;
//...
protected $commands = [
Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];
更新:
此功能对 Late Static Binding 也很有用。
您可以使用static::class 功能来获取父类中派生类的名称,而不是使用__CLASS__ 魔术常量。例如:
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
【讨论】:
Inspire::class 等同于“App\Console\Commands\Inspire”,没有反斜杠前缀。
use \App\... 和use App\... 这两个符号是允许的。我用它来区分包含在子命名空间中的类和包含在当前命名空间层次结构之外的类。
class比较特殊,是php提供的,用来获取全限定类名。
见http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name。
<?php
class foo {
const test = 'foobar!';
}
echo foo::test; // print foobar!
【讨论】:
如果您好奇它属于哪个类别(是否是语言构造等),
这只是一个常数。
PHP 称它为“特殊常量”。它的特殊之处在于它是 PHP 在编译时提供的。
特殊的 ::class 常量自 PHP 5.5.0 起可用,并允许 对于编译时的完全限定类名解析,这是 对命名空间类有用:
【讨论】:
请注意使用以下内容:
if ($whatever instanceof static::class) {...}
这将引发语法错误:
unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'
但您可以改为执行以下操作:
if ($whatever instanceof static) {...}
或
$class = static::class;
if ($whatever instanceof $class) {...}
【讨论】:
$className = 'SomeCLass'; $className = new $className(); $methodName = 'someMethod'; $className->$methodName($arg1, $arg2, $arg3); /* or if args can be random array*/ call_user_func_array([$className, $methodName], $arg);