我有一個運行一些相當通用的代碼的功能,這些代碼可以很多工作連接到數據庫並設置不同的配置變量。讓我們不要涉及這個道德問題,請和我一起裸露。我有幾個這樣的頂級函數代碼的聲明,我運行它實際上是不同的函數。創建函數接受函數
這就是它現在的樣子。
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);
}
我在尋找更好的,烘乾機,以及更易於維護的代碼。
您可能正在尋找一個回調[call_user_func](http://php.net/manual/en/function.call-user-func.php)? –