覆盖自定义函数值


Override a custom function value

我目前正处于使用带有"call_user_func"的自定义代码重写函数值的阶段。函数名称为"admin_branding",它可以满足其他函数重写其默认值的需要。

用法

<?php echo admin_branding(); ?>

从上面的函数中,结果是"示例1",但结果应该是"示例2

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函数。

如果你想模仿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

您可以检查http://php.net/manual/de/function.call-user-func.php来自PhP手册。它不会"覆盖"某些内容,实际上它只是调用您的第一个函数。

在我的评论的基础上,我起草了一个非常。关于我将如何实现这样一件事的非常基本的场景:

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"