调用参数中定义的方法作为回退


Calling a method defined in parameter as fallback

我怀疑解决这个问题的最佳方法是:

我想做的是能够调用一个方法,该方法将首先验证我需要的数据是否在缓存中,然后如果不可用,则执行我定义为原始方法上的参数的回退方法。

public function index() {
    $data['some_cache'] = $this->get_cache('cache_key', $this->get_list_something('entered fallback method'));
}
public function get_cache($key, $fallback_function) {
    $data = FALSE;
    if ( ! empty($key)) {
        $data = $this->cache($key);
        if (empty($data)) {
            $data = $fallback_function;
        }
    }
    return $data;
}
public function cache($key) {
    // try to find something on cache list (either memory cache / file cache) I just return FALSE to fail on purpose
    return FALSE;
}
public function get_list_something($param) {
    return $param;
}

我可以将方法名称作为字符串发送,将参数作为数组发送,然后使用call_user_func_array调用它(导致get_cache方法发生更改)。

因此,我的问题归结为:这是一种好的做法吗?这样做会遇到什么问题?

谢谢你的帮助。

试试这个,user_call_method()或user_call_function()

我假设你在这里使用的是类方法,而不是基于$this 使用的常规函数

所以试试这个,也许你会从中得到一些想法。

<?php
  class test {
    public function index() {
      $data['some_cache'] = $this->get_cache('cache_key', 'get_list_something','test','test2');
      return $data['some_cache'];
    }
    public function get_cache($key, $fallback_function) {
      $data = FALSE;
      if ( ! empty($key)) {
        $data = $this->cache($key);
        $args = func_get_args(); // Dynamically Pass Arguments optional    
        unset($args[0]); unset($args[1]); // Unset the cach_key, and method name get_list_something   
        if ($data==false) {
          $data = @call_user_method($fallback_function,$this,$args);
        }
      }
      return $data;
    }
    public function cache($key) {
      $flag = false;
      $words = ($flag)?'true':'false';
      echo 'cache returning <b>'.$words.'</b>, testing <b>fallback_function</b><br>'; 
      return $flag;
    }
    public function get_list_something(&$args) { 
      $params = implode(',',$args);  
      echo 'running <b>fallback_function</b><br>';
      return $params;
    }
  }
  $test = new test();
  echo $test->index();
?>