首頁  >  文章  >  後端開發  >  laravel裡應用物件$app,寫成$app[$k] 竟然不報錯!為何?

laravel裡應用物件$app,寫成$app[$k] 竟然不報錯!為何?

WBOY
WBOY原創
2016-12-01 01:27:431218瀏覽

laravel 5.1裡的
IlluminatesystemFilesystemManager 類別中的
getConfig方法中
竟然用

<code class="php">$this->app['config']["filesystems.disks.{$name}"]);</code>

返回數組。

但是

<code class="php">$this->app</code>

明明是個對像啊。
物件能用陣列的鍵值取值嗎? 這在文法上明明是錯的但是神奇的事情還是發生了

這是getConfig方法

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

我單獨dd($this->app);
即如下

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

輸出

laravel裡應用物件$app,寫成$app[$k] 竟然不報錯!為何?

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

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

那麼輸出如下

laravel裡應用物件$app,寫成$app[$k] 竟然不報錯!為何?

總之 $app 明明是個對象,怎麼能寫成 $app[$k] 這樣的形式呢?

回覆內容:

laravel 5.1裡的
IlluminatesystemFilesystemManager 類別中的
getConfig方法中
竟然用

<code class="php">$this->app['config']["filesystems.disks.{$name}"]);</code>

返回數組。

但是

<code class="php">$this->app</code>

明明是個對像啊。
物件能用陣列的鍵值取值嗎? 這在文法上明明是錯的但是神奇的事情還是發生了

這是getConfig方法

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

我單獨dd($this->app);
即如下

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

輸出

laravel裡應用物件$app,寫成$app[$k] 竟然不報錯!為何?

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

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

那麼輸出如下

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn