今天我29年3月5日在做PHP的東西有點棘手。我在一個場景中,我必須連鎖func_get_args
,call_user_func_array
,並通過一些通過引用的參數。結合func_get_args,call_user_func_array,並引用傳遞
在簡化方案的嘗試看起來是這樣的:
caller.php
//* Caller Setup *//
// Define which Modules call which Hooks
global $hooks = array(
'hookA' => array('moduleA', 'moduleB'),
'hookB' => array('moduleA')
);
// Generically calls any Hook for all Modules
function caller_call_hook($hook, $by_reference = array())
{
// Use Hooks Array
global $hooks;
// Initialize Return Array
$values = array();
// Determine the Arguments for the Function Call
$args = func_get_args();
// Remove $hook and $by_reference from the Arguments
unset($args[0], $args[1]);
$args = array_values($args); // Collapse Array
// Map specified Arguments by Reference
foreach($by_reference as $index)
$args[$index] =& $args[$index];
// Call each Embedded Hook
foreach($hooks[$hook] as $module)
$values[$module] = call_user_func_array($module . '_' . $hook, $args);
// Return all Values
return $values;
}
//* Caller Triggers *//
function caller_hook_A($paramA, $paramB)
{
caller_call_hook('hook_A', array(), $paramA, $paramB);
}
function caller_hook_B(&$paramA)
{
caller_call_hook('hook_B', array(0), $paramA);
}
moduleA.php
function moduleA_hook_A($paramA, $paramB) { ... }
function moduleA_hook_B(&$paramA) { ... }
moduleB.php
function moduleB_hook_A($paramA, $paramB) { ... }
做這一切引發了警告:
Warning: Parameter 1 to moduleA_hook_B() expected to be a reference, value given in caller_call_hook()
我怎樣才能使這項工作按照預期?
只是提供一些背景,以什麼實際發生在這裏:
我在一個框架,caller_hook_*
由框架調用工作。我基本上使用調用者作爲轉換「代碼中心」,其中我的代碼中的各種功能是分開處理的。
不,我不能把這個項目分成多個項目。這是對我的限制。通常情況下,這將是我會採取的路線。
的module*
功能,我想能夠輕鬆打開和關閉基本上內部特徵。由於模塊本身沒有交叉,所以它們故意將文件分開,除了它們有時使用相同的鉤子。
鉤子本身的所有配置都在$hooks
變量中處理(這是一個簡化版本,通常也有每個模塊的功能屬性,模塊屬性等,但這不是特別需要解決的問題。)。
我試圖儘可能地保持這種一般化。我知道我可以在各自的功能中推動一切,但隨着此項目的發展,如果獨立功能聚集在一起,這些掛鉤將變得非常麻煩。
一些鉤子使用傳遞引用對他們的一些參數,因此我需要能夠指定哪些。我迄今爲止所做的一切都適用於所有傳遞值唯一的功能。
我也不想使用通話時間通過引用。
什麼是$ args [$ index] =&$ args [$ index]'應該這樣做?怎樣才能成爲對自身的參照? – Barmar
應該是'$ args [$ index] =&$ by_reference [$ index];'? – Barmar
我來自C++背景,所以我可能在這裏使用引用不正確。你會推薦什麼? – Boom