创建接受函数的函数

时间:2012-05-21 13:46:40

标签: php 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);

}

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

1 个答案:

答案 0 :(得分:1)

这是PHP调用variable functions的东西。当$inner是函数的字符串名称和anonymous function时,这都有效(尽管变量函数的手册页没有解释)。

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

      }
    }
  }
}