Laravel如何在静态方法中使用$ this上下文? [英] How laravel use $this context in static methods?

查看:558
本文介绍了Laravel如何在静态方法中使用$ this上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How does Laravel uses $this->comment() method inside console.php file in "routes" directory while Artisan::command() being a static method?

<?php

use Illuminate\Foundation\Inspiring;

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

推荐答案

$this不在静态方法本身内部使用,而是在传递给该方法的闭包中使用. 从Laravel手册中:

$this isn't being used inside the static method itself, it's used in the closure that's passed to that method. 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 方法实现的,该方法可以指定任何给定闭包的范围.

So $this in this context is a Command instance. This is achieved using PHP's bindTo method, which allows you to specify the scope for any given closure.

这种方法并非Artisan命令专有.通常,我们将此功能称为 Facades :

This kind of methods are not exclusive to Artisan commands though. In general, we call this feature Facades:

外观为应用程序的服务容器中可用的类提供了静态"接口. . Laravel附带了许多外墙,可以访问Laravel的几乎所有功能. Laravel外观作为服务容器中基础类的静态代理",提供了简洁,表达性强的语法的优点,同时保持了比传统静态方法更高的可测试性和灵活性.

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.

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

There are quite some other facades, which all provide static access to instances that live within the service container. Some of the more common facades and methods are:

  • Cache::get('key')Cache::set('key', 'value')
  • Request::input('some_field')Request::only('some_field')
  • Log::info('be aware of this...')
  • ...
  • Cache::get('key') and Cache::set('key', 'value')
  • Request::input('some_field') and Request::only('some_field')
  • Log::info('be aware of this...')
  • ...

这篇关于Laravel如何在静态方法中使用$ this上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆