php类函数包装器

Pat*_*ick 4 php oop

这是我的班级:

class toyota extends car {
    function drive() {
    }
    function break() {
    }
}

class car {
    function pre() {
    }
}
Run Code Online (Sandbox Code Playgroud)

我有什么方法可以这样做,当我运行$ car-> drive(),$ car-> break()(或丰田中的任何其他函数)时,它会先调用$ car-> pre()然后再调用丰田的功能?

zer*_*kms 12

是的.你可以用protected一些__call魔法:

class toyota extends car {
    protected function drive() {
        echo "drive\n";
    }
    protected function dobreak() {
        echo "break\n";
    }
}

class car {
    public function __call($name, $args)
    {
        if (method_exists($this, $name)) {
            $this->pre();
            return call_user_func_array(array($this, $name), $args);
        }


    }

    function pre() {
        echo "pre\n";
    }
}

$car = new toyota();
$car->drive();
$car->dobreak();
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/SGi1g