Reputation: 73
I'm developing a custom ORM and here's a simplified example to demo the issue:
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 same method when called inside Foo triggers __call
and inside Foo2
triggers __callStatic
?
Upvotes: 2
Views: 268
Reputation: 6379
Thats because in the first call where you get Null
returned, your in an object context. So it is calling __call()
instead of __callStatic()
.
EDIT: In the first case, Foo::getBar() is called in the scope of an instance of class Foo, so Foo::getBar() is actually the same as (instance)->getBar() which of course isn't a static call.
EDIT2: Just found a question + answer regarding your question: Why does PHP prefer __call() to __callStatic()?
Upvotes: 2