• 技术文章 >后端开发 >php教程

    Laravel 中static方法为什么在相应的类中找不到

    2016-06-06 20:39:09原创452
    有一个名称为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

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:laravel php
    上一篇:想在CMD 窗口执行PHP文件,在windows8.1 64位系统下如何配置? 下一篇:php的一些疑惑
    大前端线上培训班

    相关文章推荐

    • 带你分清类中的构造函数与析构函数• PHP中的命名空间定义与使用(实例详解)• PHP中clone关键字和__clone()方法的使用(实例详解)• 五分钟带你了解PHP中的魔术方法(实例详解)• 怎样去搞定PHP类的继承?(总结分享)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网