簡體   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