php - 如何在同一个类上使用同名的静态方法和实例方法?
问题描述
我正在尝试重新创建 Laravel ORM(Eloquent )。
在 Laravel 中,我们可以这样做:
Model::where("condition1")->where("condition2")->get();
到目前为止,我尝试重新创建它导致我编写以下代码:
class DB {
static $condition ;
public static function chidlClassName() {
return get_called_class();
}
static function where( $cond ) {
self::$condition[] = $cond;
return new DB();
}
public function where( $cond ){
self::$condition[] = $cond ;
return $this;
}
function get(){
$cond = implode(' AND ' ,self::$condition);
}
}
class Modle extends DB {}
但它不会工作,因为这两个where
函数具有相同的名称......
Laravel 是如何做到的?
解决方案
我还没有看到 Eloquent 是如何做到的,但实现这一点的方法不是在基类和扩展类中声明要重用的方法;而是使用魔术方法 __call($method, $arguments)
和__callStatic($method, $arguments)
.
一个简单的例子是这样的:
class Base {
public static function __callStatic($method, $arguments) {
if ('foo' === $method) {
echo "static fooing\n";
}
return new static();
}
public function __call($method, $arguments) {
if ('foo' === $method) {
echo "instance fooing\n";
}
}
}
class Child extends Base {
}
这将用作:
Child::foo()->foo();
第一个在类中foo()
通过,因为它是一个静态调用。第二个通过,因为它是一个非静态调用。__callStatic()
Base
foo()
__call()
这将输出:
static fooing
instance fooing
你可以看到它在这里工作。