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();

http://ideone.com/SGi1g

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() {
    }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!