【问题标题】:Laravel -- Why the `::class` ConstantLaravel -- 为什么使用 `::class` 常量
【发布时间】:2015-08-19 18:22:27
【问题描述】:

在 Laravel 5.1 中,CLI 类的内核看起来像这样

#File: app/Console/Kernel.php
class Kernel extends ConsoleKernel
{
    //...    
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];
    //...
}

是否改为使用预定义/魔术常量::class

\App\Console\Commands\Inspire::class

在功能上与简单地使用类名不同吗?

\App\Console\Commands\Inspire

【问题讨论】:

    标签: php class laravel constants


    【解决方案1】:

    不,在类上使用 ::class 会返回完全限定的类名,因此它与编写 'App\Console\Commands\Inspire' 相同(用引号括起来,因为它是一个字符串)。 class 关键字是 PHP 5.5 的新关键字。

    在这个例子中看起来很傻,但它可以在例如测试或定义关系。例如,如果我有一个 Article 类和一个 ArticleComment 类,我可能最终会这样做

    use Some\Long\Namespace\ArticleComment;
    
    class Article extends Model {
    
        public function comments()
        {
            return $this->hasMany(ArticleComment::class);
        }
    
    }
    

    参考:PHP Docs

    【讨论】:

    • Derp,谢谢!我忘记了包括用字符串包围类名的旧方法(因为 PHP 不会标记自己周围的类名)。
    【解决方案2】:

    对于执行代码并没有什么不同,但::class 常量对于开发工具最有用。如果您使用类名,则必须将其写为字符串'\App\Console\Commands\Inspire' - 这意味着:

    1. 没有 IDE 自动完成
    2. 不支持自动重构(“重命名类”)
    3. 没有命名空间解析
    4. 无法自动检测使用情况 (IDE) 或依赖关系 (pDepend)

    旁注:在 PHP 5.5 出来之前,我曾经在我自己的大多数类中定义一个常量 __CLASS 正是为了这个目的:

    class X {
        const __CLASS = __CLASS__;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 2018-01-04
      • 2014-02-09
      • 1970-01-01
      相关资源
      最近更新 更多