如何在同一类上使用具有相同名称的静态方法和实例方法?

时间:2019-08-10 17:40:53

标签: php laravel oop

我正在尝试重新创建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如何做到?

1 个答案:

答案 0 :(得分:1)

我还没有看到Eloquent如何做到这一点,但是实现这一目标的方法将在基类和扩展类中都声明要重用的方法。而是使用the magic methods __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

您可以看到它在here下工作。