Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's magic method __call on subclasses

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?

like image 262
nickf Avatar asked Oct 08 '09 01:10

nickf


2 Answers

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.

like image 64
Santiago Garibotto Avatar answered Nov 04 '22 09:11

Santiago Garibotto


__call() is only invoked when the function isn't otherwise found so your example, as written, is not possible.

like image 41
cletus Avatar answered Nov 04 '22 08:11

cletus