PHP methods that are always called

I am currently working on my own PHP-MVC-Framework (for experimental purposes only).

My question is: is it possible to call a specific function or method, every time a class method has been called?

For instance:

public function view($id) { //Code ... $this->view->render(__FUNCTION__); } 

I want to:

 public function view($id) { //Code ... //render-method is called automatically with functionname as parameter } 

I tried different methods ... but to no avail. It would be great if someone could help me with this.

Cheers, Chris

+4
source share
3 answers

You can use Magic Methods to achieve this behavior:

 public function __call($func, $args) { if(!method_exists($this, $func)) { return; } // do some coding here call_user_func_array($func,$args); // do some coding there } private function view($arg1, $arg2) { // and here } 

Remember: the viewing function must be private / secure.

 $obj->view("asdasd", "asdsad"); 

Must execute :: __ call (), then :: view () method

+5
source

You can create a function as a connection using PHP's ability to use the values โ€‹โ€‹of variables to execute. eg:

 function call($func,$param) { $this->$func($param); $this->render($func); } $myObj->call('view',$id); 
+1
source

You can use the wrapper method. Call this method and pass everything else as parameters.

+1
source

Source: https://habr.com/ru/post/1333476/


All Articles