PHP: __call is called instead of __callStatic

I am developing a custom ORM and here is a simplified example to demonstrate the problem:

class Foo {
    public static function __callStatic($name, $args){
        if($name == "getBar"){
            return "Bar";
        }
        return NULL;
    }

    public function __call($name, $args){
        if($name == "getFoo"){
            $model = "Foo";
            $method = "getBar";            
            return $model::$method();            
        }
        return NULL;
    }
}

class Foo2 {
    public function __call($name, $args){
        if($name == "getFoo"){
            $model = "Foo";
            $method = "getBar";            
            return $model::$method();            
        }
        return NULL;
    }
}

echo Foo::getBar();//Bar

$foo = new Foo;
var_dump($foo->getFoo()); //Null though I'm expecting Bar

$foo = new Foo2;
var_dump($foo->getFoo()); //Bar

So, why is the method called inside Foo triggers __calland inside Foo2triggers __callStatic?

+1
source share
1 answer

Thats because in the first call where you get Null, your object is returned in the context of the object. Therefore, it calls __call()instead __callStatic().

EDIT: In the first case, Foo :: getBar () is called on the instance scope of the Foo class, so Foo :: getBar () actually matches (instance) -> getBar (), which of course is not a static call.

EDIT2: + : PHP __call() __callStatic()? p >

+1

Source: https://habr.com/ru/post/1663927/


All Articles