2015-11-03 79 views
0

我有兩個函數,它們附在鉤子上,並在程序生命週期中的指定點或事件中執行。當我們想要將一個函數調用的某些返回值傳遞給另一個函數調用時,通過函數和設計,什麼纔是最好的方法,但是沒有重複的函數調用或者污染全局作用域。如何在不重複函數調用或污染全局作用域的情況下從函數返回值?

這裏就是我希望的代碼有據可查的部分:

/** 
* @array hookparams Hookparams array from both of function calls 
*/ 
$hookparams = []; // initalized empty values 

function hook_FunctionOne() 
{ 
    //do something, than save result in hookparams array 
    $hookparams['key'] = "Foo"; // return? But I can't call FunctionOne once more, and assign return value to temp variable 
} 

function hook_FunctionTwo(array $hookparams) 
{ 
    //do something with returned hookparams array form function, than save result in hookparams array again 
    $hookparams['key'] .= "Bar"; // Result is "FooBar"; 
} 

// Both functions are called here 

run_hook("HookPoint1", "hook_FunctionOne"); 
run_hook("HookPoint2", "hook_FunctionTwo"); 

回答

0

按引用傳遞參數給函數救了我的day.Here是完整的代碼:

/** 
* @array hookparams Hookparams array from both of function calls 
*/ 
$hookparams = []; // initalized empty values 

function hook_FunctionOne(&$hookparams) 
{ 
    //do something, than save result in hookparams array 
    return $hookparams['key'] = "Foo"; // return? But I can't call FunctionOne once more, and assign return value to temp variable 
} 

function hook_FunctionTwo(&$hookparams) 
{ 
    //do something with returned hookparams array form function, than save result in hookparams array again 
    return $hookparams['key'] .= "Bar"; // Result is "FooBar"; 
} 

// Both functions are called here 

echo hook_FunctionOne($hookparams); // First function call 

echo hook_FunctionTwo($hookparams); // Second function call 

echo "<pre>"; 
print_r($hookparams); 
echo "</pre>" 
相關問題