March 28, 2012
php class function wrapper
Question by Patrick
this is my class:
class toyota extends car {
function drive() {
}
function break() {
}
}
class car {
function pre() {
}
}
Is there any way I can do so that when I run $car->drive(), $car->break() (or any other function in toyota), it would call $car->pre() first before calling the functions in toyota?
Answer by zerkms
Yep. You could use protected
and some __call
magic:
class toyota extends car {
protected function drive() {
echo "driven";
}
protected function dobreak() {
echo "breakn";
}
}
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 "pren";
}
}
$car = new toyota();
$car->drive();
$car->dobreak();
Answer by Starx
This will better done with the magic methods called __call()
public function __call($name, $arguments)
{
$this -> pre();
return $this -> $name($arguments);
}
What is this method? It overrides the default method call, so that preCall
State can be invoked.
Your toyota
class
class toyota extends car {
public function __call($name, $arguments)
{
$this -> pre();
return call_user_func_array(array($this, $name), $arguments);
}
function drive() {
}
function break() {
}
}