<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public static function getList()
{
return self::get()->toArray();
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected function getList()
{
return $this->get()->toArray();
}
}
class Model
{
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->forwardCallTo($this->newQuery(), $method, $parameters);
}
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
}
我们试着自已实现下这两个魔术方法,看看效果。
<?php
namespace App\Models;
class Model
{
//在对象中调用一个不可访问方法时,__call()被调用
public function __call($method, $parameters)
{
echo '__call()';
return $this->{$method}(...$parameters);
}
//在静态上下文中调用一个不可访问方法时,__callStatic()被调用
public static function __callStatic($method, $parameters)
{
echo '__callStatic()';
//注意这里,通过延迟静态绑定,仍然new了一个实例
return (new static)->{$method}(...$parameters);
}
private function test()
{
echo '被调用了<br>';
}
}
我们尝试调用 test() 方法。
<?php
namespace App\Http\Controllers\Test;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Model;
class Test extends Controller
{
public function index(Request $request)
{
//对象调用
(new Model())->test();
//静态方法调用
Model::test();
}
}