2014-10-18 62 views
2

我目前被卡在一個點,在這裏我正在使用自定義代碼覆蓋函數值,其中「call_user_func」。功能名稱爲「admin_branding」,可以滿足其他功能覆蓋它的默認值。覆蓋自定義函數值

用法

<?php echo admin_branding(); ?> 

從上面的功能,結果是 「實施例1」 但結果應該是 「實施例2」,因爲現在用的「的add_filter覆蓋它的值「

PHP代碼

/* Custom function with its custom value */ 
function custom_admin_branding(){ 
    return "Example 2"; 
} 

/* Default function with its default value */ 
function admin_branding($arg = ''){ 
    if($arg){ $var = $arg(); 
    } else { $var = "Example 1"; } 
    return $var; 
} 

/* Call User function which override the function value */ 
function add_filter($hook = '', $function = ''){ 
    call_user_func($hook , "$function"); 
} 

/* Passing function value to override and argument as custom function */ 
add_filter("admin_branding", "custom_admin_branding"); 

一個很好的例子是WordPress如何使用自定義的add_filter函數。

+0

你問如何取消設置功能? – Tim 2014-10-18 22:02:04

+0

實際上,我正在嘗試使用像WordPress這樣的add_filter函數。 – 2014-10-18 22:06:46

+1

爲什麼你認爲你正在覆蓋「它的價值」('admin_branding()')? 'call_user_func'會立即調用'custom_admin_branding'而不是替換任何東西。 – Niko 2014-10-18 22:08:05

回答

1

如果你想模仿的WordPress(不推薦這雖然):

$filters = array(); 

function add_filter($hook, $functionName){ 
    global $filters; 
    if (!isset($filters[$hook])) { 
     $filters[$hook] = array(); 
    } 
    $filters[$hook][] = $functionName; 
} 

function apply_filters($hook, $value) { 
    global $filters; 
    if (isset($filters[$hook])) { 
     foreach ($filters[$hook] as $function) { 
      $value = call_user_func($function, $value); 
     } 
    } 
    return $value; 
} 

// ---------------------------------------------------------- 

function custom_admin_branding($originalBranding) { 
    return "Example 2"; 
} 

function admin_branding() { 
    $defaultValue = "Example 1"; 
    return apply_filters("admin_branding", $defaultValue); // apply filters here! 
} 

echo admin_branding(); // before adding the filter -> Example 1 
add_filter("admin_branding", "custom_admin_branding"); 
echo admin_branding(); // after adding the filter -> Example 2 
+0

謝謝,這正是我期待的。 – 2014-10-18 22:40:31

1

擴大我的評論,我畫了一個非常。在我將如何實現這樣的事情很基本的場景:

的index.php

include "OverRides.php"; 
function Test(){ 
    return true; 
} 
function Call_OverRides($NameSpace, $FunctionName, $Value = array()){ 
    $Function_Call = call_user_func($NameSpace.'\\'.$FunctionName,$Value); 
    return $Function_Call; // return the returns from your overrides 

} 

OverRides.php

namespace OverRides; 
    function Test($Test){ 
     return $Test; 
    } 

不積極測試,概念流經實施雖然

調試:

echo "<pre>"; 
var_dump(Test()); // Output: bool(true) 
echo "<br><br>"; 
var_dump(Call_OverRides('OverRides','Test',"Parameter")); // Output: string(9) "Parameter" 
+0

到新命名空間的路由如果需要對工作結構/後端處理。我很樂意根據要求提供 – 2014-10-18 22:27:30