创建接受函数的函数


Create function that accepts function

我有一个函数,它运行一些相当通用的代码,这些代码可以与数据库进行大量工作连接并设置不同的配置变量。我运行的这个顶级函数代码的几个 if 语句实际上因函数而异。

这就是它现在的样子。

function get_users(){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */
        // the code here varies from function to function
        // eg. get users
        // probably will run: inner_get_users();
      }
    }
  }
}
function get_data(){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */
        // the code here varies from function to function
        // eg. get data
        // probably will run: inner_get_data();
      }
    }
  }
}

我希望它如何工作,也许使用匿名函数:

function instance($inner){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */
        Call inner
      }
    }
  }
}
function get_data(){
  instance(function(
    // get the data
  ));
}

或者也许

function get_users(){
  $var = function(
    // get the users
  );
  instance($var);
}

我正在寻找更好、更干燥、更易于维护的代码。

这是

PHP称之为变量函数的东西。当$inner是函数的字符串名称时,这在匿名函数时都有效(尽管变量函数的手册页没有解释这一点(。

function instance($inner){
  // config
  // set application keys
  // connect to database
  // retrieve user data
  // authentication to foreign api
  if(something){
    // some more red-tape
    if(something){
      //more more
      if(something){
        /* finally the good stuff */
        return $inner();
      }
    }
  }
}