Well, there's no easy way to do this, but it is possible. Still, the way you'll have to go about achieving this is not to be recommended, as it will result in slow code. However, here's a simple way to do this:
class Foo
{
//protected, not public
protected static function bar ()
{
}
protected function nonStaticBar()
{
}
public function __call($method, array $args)
{
//echoes you called Foo::nonStaticBar
printf('You called %s::%s', get_class($this), $method);
//perform the actual call
return call_user_func_array([$this, $method], $args);
}
//same, but for static methods
public static function __callStatic($method, array $args)
{
$calledClass = get_called_class();//for late static binding
printf('You called %s::%s statically', $calledClass, $method);
return call_user_func_array($calledClass . '::' . $method, $args);
}
}
$foo = new Foo;
$foo->nonStaticBar();//output: You called Foo::nonStaticBar
Foo::bar();//output: You called Foo::bar statically
The reason for __callStatic
using get_called_class
rather than get_class(self);
is that it enables you to declare the magic methods as final
, and still have them work as expected in child classes:
class Foobar extends Foo
{}
Foobar::bar();//output: You called Foobar::bar statically
more details on magic methods: