欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

laravel里应用对象$app,写成$app[$k] 竟然不报错!为何?

程序员文章站 2022-05-08 18:18:02
...

laravel 5.1里的
IlluminateFilesystemFilesystemManager 类中的
getConfig方法中
竟然用

$this->app['config']["filesystems.disks.{$name}"]);

返回数组。

但是

$this->app

明明是个对象啊。
对象能用数组的键值取值吗? 这在语法上明明是错的但是神奇的事情还是发生了

这是getConfig方法

 /**
     * Get the filesystem connection configuration.
     *
     * @param  string  $name
     * @return array
     */
    protected function getConfig($name)
    {
       
        return $this->app['config']["filesystems.disks.{$name}"];
    }

我单独dd($this->app);
即如下

 /**
     * Get the filesystem connection configuration.
     *
     * @param  string  $name
     * @return array
     */
    protected function getConfig($name)
    {
        dd($this->app);
        return $this->app['config']["filesystems.disks.{$name}"];
    }

输出

laravel里应用对象$app,写成$app[$k] 竟然不报错!为何?

但是我dd($this->app'config');即

 protected function getConfig($name)
    {
        dd($this->app['config']["filesystems.disks.{$name}"]);
        return $this->app['config']["filesystems.disks.{$name}"];
    }

那么输出如下

laravel里应用对象$app,写成$app[$k] 竟然不报错!为何?

总之 $app 明明是个对象,怎么能写成 $app[$k] 这样的形式呢?

回复内容:

laravel 5.1里的
IlluminateFilesystemFilesystemManager 类中的
getConfig方法中
竟然用

$this->app['config']["filesystems.disks.{$name}"]);

返回数组。

但是

$this->app

明明是个对象啊。
对象能用数组的键值取值吗? 这在语法上明明是错的但是神奇的事情还是发生了

这是getConfig方法

 /**
     * Get the filesystem connection configuration.
     *
     * @param  string  $name
     * @return array
     */
    protected function getConfig($name)
    {
       
        return $this->app['config']["filesystems.disks.{$name}"];
    }

我单独dd($this->app);
即如下

 /**
     * Get the filesystem connection configuration.
     *
     * @param  string  $name
     * @return array
     */
    protected function getConfig($name)
    {
        dd($this->app);
        return $this->app['config']["filesystems.disks.{$name}"];
    }

输出

laravel里应用对象$app,写成$app[$k] 竟然不报错!为何?

但是我dd($this->app'config');即

 protected function getConfig($name)
    {
        dd($this->app['config']["filesystems.disks.{$name}"]);
        return $this->app['config']["filesystems.disks.{$name}"];
    }

那么输出如下

laravel里应用对象$app,写成$app[$k] 竟然不报错!为何?

总之 $app 明明是个对象,怎么能写成 $app[$k] 这样的形式呢?

app继承自 IlluminateContainerContainer, 而 Container 实现了ArrayAccess(http://php.net/manual/zh/clas...)接口。ArrayAccess接口提供了像访问数组一样访问对象的能力,只要实现接口的几个方法就可以调用 isset, unset, []方式存取值。

$this->app['config'] 也是个对象 IlluminateConfigRepository 它也实现了 ArrayAccess ,所以也能当数组用。

ArrayAccess

相关标签: laravel php