My situation is best described with a bit of code:
class Foo {
function bar () {
echo "called Foo::bar()";
}
}
class SubFoo extends Foo {
function __call($func) {
if ($func == "bar") {
echo "intercepted bar()!";
}
}
}
$subFoo = new SubFoo();
// what actually happens:
$subFoo->bar(); // "called Foo:bar()"
// what would be nice:
$subFoo->bar(); // "intercepted bar()!"
I know I can get this to work by redefining bar()
(and all the other relevant methods) in the sub-class, but for my purposes, it'd be nice if the __call
function could handle them. It'd just make things a lot neater and more manageable.
Is this possible in PHP?
__call()
is only invoked when the function isn't otherwise found so your example, as written, is not possible.What you could do to have the same effect is the following:
If you need to add something extra to the parent bar(), would this be doable?
or is this just a question from curiosity?
It can't be done directly, but this is one possible alternative:
This sort of thing is good for debugging and testing, but you want to avoid
__call()
and friends as much as possible in production code as they are not very efficient.One thing you can try is to set your functions scope to private or protected. When one private function is called from outside the class it calls the __call magic method and you can exploit it.