什么是PHP中的类?

时间:2015-06-11 01:36:55

标签: php class laravel

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

由于语法的性质,快速Google搜索不会返回任何内容。

冒号结肠类

使用这种表示法的优点是什么?

protected $commands = [
    \App\Console\Commands\Inspire::class,
];

4 个答案:

答案 0 :(得分:61)

此功能在PHP 5.5中实现。

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

由于两个原因它非常有用。

  • 您不必再将字符串存储在字符串中。因此,许多IDE可以在您重构代码时检索这些类名称
  • 您可以使用use关键字来解析课程,而且不需要编写完整的课程名称。

例如:

use \App\Console\Commands\Inspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];

更新

此功能对 Late Static Binding 也很有用。

您可以使用__CLASS__功能获取父类中派生类的名称,而不是使用static::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

答案 1 :(得分:17)

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!

答案 2 :(得分:2)

如果您想知道它属于哪个类别(是否是语言构造等),

它只是一个常量

PHP将其称为“特殊常量”。这很特别,因为它是PHP在编译时提供的。

特殊的:: class常量自PHP 5.5.0起可用,并且允许 为了在编译时解析完全合格的类名,这是 对于命名空间类有用:

https://www.php.net/manual/en/language.oop5.constants.php

答案 3 :(得分:1)

请注意使用以下内容:

if ($whatever instanceof static::class) {...}

这将引发语法错误:

  

意外的课程&#39; (T_CLASS),期待变量(T_VARIABLE)或&#39; $&#39;

但你可以改为:

$class = static::class;
if ($whatever instanceof $class) {...}

也许这已在PHP 7中修复。