覆盖自定义函数值

时间:2014-10-18 21:48:01

标签: php

我'我目前停留在使用" call_user_func "的自定义代码覆盖函数值的位置。功能名称为" admin_branding "这可以满足其他功能,以覆盖它的默认值。

用法

<?php echo admin_branding(); ?>

从上述功能中,结果为&#34; 示例1 &#34;但结果应该是&#34; 示例2 &#34;因为我使用&#34; add_filter &#34;

覆盖其值

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 功能。

3 个答案:

答案 0 :(得分:1)

您可以从PhP手册中查看http://php.net/manual/de/function.call-user-func.php。 它没有“覆盖”某些东西,实际上它只是调用你的第一个函数。

答案 1 :(得分: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"

答案 2 :(得分: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