Laravel 中static方法為什麼在相應的類中找不到

來源:互聯網
上載者:User
有一個名稱為Shop的model,可以使用 Shop::where("id",14)->first()
但在 Illuminate\Database\Eloquent\Model中卻找不到where方法。不過在555行找到了使用 where的代碼:

if ( ! is_null($instance = static::where($attributes)->first())){    return $instance;}

這裡的static::where()是怎麼回事,Shop::where()是調用的哪裡的where方法

回複內容:

有一個名稱為Shop的model,可以使用Shop::where("id",14)->first()
但在Illuminate\Database\Eloquent\Model中卻找不到where方法。不過在555行找到了使用where的代碼:

if ( ! is_null($instance = static::where($attributes)->first())){    return $instance;}

這裡的static::where()是怎麼回事,Shop::where()是調用的哪裡的where方法

看這一行代碼
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3354

phppublic static function __callStatic($method, $parameters){    $instance = new static;    return call_user_func_array(array($instance, $method), $parameters);}

意思是如果靜態方法找不到,會嘗試執行個體化之後再次調用對象方法

Model::where()到這裡會變成$model->where()

再繼續看
https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L3335
這行代碼

phppublic function __call($method, $parameters){    if (in_array($method, array('increment', 'decrement')))    {        return call_user_func_array(array($this, $method), $parameters);    }    $query = $this->newQuery();    return call_user_func_array(array($query, $method), $parameters);}

意思是如果本身再沒有->where()這個方法,會再次嘗試執行個體化一個\Illuminate\Database\Eloquent\Builder對象並填充當前已經設定過的一些參數,再進行操作

到這裡Model::where()會變成 $model->newQuery()->where()

所以到最後,你調用到的是

phpnew \Illuminate\Database\Eloquent\Builder()->where()

這個方法

vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php#384-457

補充:http://v4.golaravel.com/docs/4.2/facades

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.