coding时候思维定式,就写出了这样的代码
$model = xxxModel::class;
$model::from($model::getTable() . ' as ' . $tableAlia);
运行错误提示: getTable 是non-static 不可以静态调用;
于是 想起
一 : Model::where() 是ok的
二: Eloquent\Model 类是有__callStatic的
没细想就搜了网上,于是 有人问了这个问题 但是网上搬出来的是 鸟哥的关于 静态方法的判断不是根据 ::符号,而是根据调用的上下文--calling scope .
但是提问随后抛出 where 为何正常;
==============
理解:
如果该类存在同名方法,但是未声明为 static, 则运行阶段会根据这个情况抛错;
如果该类不存在该同名方法,则尝试走 __callStatic ;
==========================
Model::where() 实际走的是自己的__callStatic,
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
============================
因为Model类内部不存在where方法,所以又走了 __call
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
//$this->newQuery() 实例化 \Illuminate\Database\Eloquent\Builder类
return $this->newQuery()->$method(...$parameters);
}
所以 where 实际是调用的 Eloquent\Builder 的where 方法;而 getTable gg