简体   繁体   English

始终被调用的PHP方法

[英]PHP Methods that are always called

I'm currently working on an own PHP-MVC-Framework (for experience purposes only). 我目前正在开发自己的PHP-MVC-Framework(仅出于体验目的)。

My question: Is it possible to call a defined function or method, every time a class-method has been called? 我的问题:每次调用类方法时,是否可以调用已定义的函数或方法?

For example: 例如:

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

What I want is: 我想要的是:

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

I tried different methods ... but without success. 我尝试了不同的方法……但是没有成功。 Would be great if someone could help me out with this. 如果有人可以帮我解决这个问题,那就太好了。

Cheers, Chris 克里斯,干杯

You can use Magic Methods do 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: view function must be private/protected. 请记住:视图功能必须是私有的/受保护的。

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

Should do ::__call(), then ::view() method 应该先执行:: __ call(),然后再执行:: view()方法

You could create a function as a liaison using PHP's ability to use variable values for execution purposes. 您可以使用PHP将变量值用于执行目的的功能来创建函数作为联络人。 for example: 例如:

function call($func,$param)
{
    $this->$func($param);
    $this->render($func);
}

$myObj->call('view',$id);

You can use a wrapper method. 您可以使用包装方法。 Call this method and pass everything else as a parameters. 调用此方法并将其他所有内容作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM