php - laravel 如何在静态方法中使用 $this 上下文?

标签 php laravel oop laravel-5 static-methods

Laravel 如何在“路由”目录中的 console.php 文件中使用 $this->comment() 方法,而 Artisan::command() 是一个静态方法?

enter image description here

<?php

use Illuminate\Foundation\Inspiring;

Artisan::command('inspire', function() {
    $this->comment(Inspiring::(quote));
})->describe('Display an inspiring quote');

最佳答案

$this 并未在静态方法本身内部使用,而是在传递给该方法的闭包中使用。 From the Laravel manual :

The Closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.

所以 $this 在此上下文中是一个 Command 实例。这是使用 PHP 的 bindTo 实现的。方法,它允许您指定任何给定闭包的范围。


不过,这种方法并不是 Artisan 命令独有的。一般来说,我们称这个特征为Facades :

Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features. Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

还有很多其他外观,它们都提供对服务容器内实例的静态访问。一些更常见的外观和方法是:

  • Cache::get('key')Cache::set('key', 'value')
  • Request::input('some_field')Request::only('some_field')
  • Log::info('注意这个...')
  • ...

关于php - laravel 如何在静态方法中使用 $this 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52610280/

相关文章:

php - 以两个为一组输出 Laravel 集合

php - 无法与主机 smtp.mailtrap.io [连接超时 #110] 使用正确的环境建立连接

php - 拉维尔 4.2 : Slow queries when using an external MySQL server

php - PDO - 查询不返回结果

javascript - 对象计时器无法正常工作(暂停按钮、播放按钮)

php - 使用 cookie 避免同一用户多次查看

php - 在 php 中将 header 添加到 file_get_contents

php - 自动部署 PHP 应用程序

php - CDbCriteria 参数绑定(bind)

c++ - 用 C++ 编写多平台实现