繁体   English   中英

覆盖自定义函数值

[英]Override a custom function value

我目前停留在使用自定义代码“ 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函数。

您可以从PhP手册中查看http://php.net/manual/de/function.call-user-func.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"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM