什么是PHP中的类?

Yad*_*ada 88 php class laravel

::classPHP中的符号是什么?

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

冒号结肠类

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

protected $commands = [
    \App\Console\Commands\Inspire::class,
];
Run Code Online (Sandbox Code Playgroud)

alp*_*yax 74

此功能在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"
];
Run Code Online (Sandbox Code Playgroud)

更新:

此功能对于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
Run Code Online (Sandbox Code Playgroud)

  • 稍微更正:在第一个示例中,`Inspire::class` 等价于“App\Console\Commands\Inspire”,没有反斜杠前缀。 (2认同)
  • 警告一句,您可以输入任何内容,但仍然会得到“类”名称。我可以输入 SomeDumbCrapThatDoesntExist::class ,如果 IDE 没有捕获它,它不会给我错误或警告。很容易犯错并错过。 (2认同)

xda*_*azz 19

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!
Run Code Online (Sandbox Code Playgroud)

  • 它不是Inspire类的常量.它是由php提供的常量.这是获取完全限定类名的快速方法.http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name (7认同)
  • 这段代码与问题有什么关系? (6认同)
  • @Yada 我相信 Laravel 使用它的原因是它让你少了一个打错字的地方。您可以使用字符串 '\App\Console\Commands\Inspire' 或 Inspire::class 来获得相同的结果,但您的 IDE 会捕获后者的语法/拼写错误,从而使其更容易调试。 (2认同)

Luc*_*nte 6

如果你很好奇它属于哪个类别(无论是语言结构等),

这只是一个常数

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

特殊的 ::class 常量从 PHP 5.5.0 开始可用,并允许在编译时进行完全限定的类名解析,这对于命名空间类很有用:

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