-1

I found one code block in Laravel like below:

/**
 * Register a "before" application filter.
 *
 * @param  \Closure|string  $callback
 * @return void
 */
public function before($callback)
{
    return $this['router']->before($callback);
}

What does $this['router'] mean at here? Can anyone explain the $this['xx'] form? Is it an array?

Rex Tsao
  • 65
  • 1
  • 13

3 Answers3

5

The fact that your variable is called $this means that it can't be an ordinary array - that variable name is reserved for the current instance of a class.

Using square brackets to access an object is a sign that the class implements that ArrayAccess interface - that is, it can be accessed using the operators normally reserved for basic arrays.

Retrieving a value from a class that implements ArrayAccess using square bracket notation invokes the class's offsetGet method, with the provided key as the $offset argument. The most common use is to allow access to a class's member variables, but the class itself can choose to perform any action in this method.

In your case, I think you're looking at the Laravel application class, which will result in the router item being returned from the dependency injection container.

iainn
  • 16,826
  • 9
  • 33
  • 40
2

$this['router'] references to router service in laravel service container. A service container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects).

see : What is the concept of Service Container in Laravel?

1

It simply means that it is an array. You use the square brackets, with a key (which can be a name (string, wrapped in quotes), or a number) to identify the proper value from the array.

In your code, $this['router'] refers to an array that contained in the class you are looking at, and that is the identifier to select what it needs, router being the key.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71