Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php class function wrapper

Tags:

oop

php

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?

like image 794
Patrick Avatar asked Dec 16 '22 02:12

Patrick


1 Answers

Yep. You could use protected and some __call magic:

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

http://ideone.com/SGi1g

like image 182
zerkms Avatar answered Jan 03 '23 17:01

zerkms