PHP的魔术方法__call在子类上

nic*_*ckf 9 php oop magic-methods

我的情况最好用一些代码来描述:

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()!"
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过bar()在子类中重新定义(以及所有其他相关方法)来实现这一点,但就我的目的而言,如果__call函数可以处理它们会很好.它会只是让事情很多整洁和更易于管理.

这可能在PHP?

cle*_*tus 14

__call() 仅在未找到该函数时调用,因此无法执行您所编写的示例.