Reputation: 1707
I' am currently stuck at a point where am overriding a function value using a custom code with "call_user_func". The function name is "admin_branding" which can cater for other function to override it's default value.
Usage
<?php echo admin_branding(); ?>
From the above function, the result is "Example 1" but the outcome should be "Example 2" because am override its value using the "add_filter"
PHP Codes
/* 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" );
A very example is how WordPress does using their custom add_filter function.
Upvotes: 2
Views: 413
Reputation: 26730
If you want to mimic WordPress (wouldn't recommend this though):
$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
Upvotes: 1
Reputation: 5524
Expanding on my comment, I have drawn up a very. Very basic scenario on how I would implement such a thing:
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;
}
Not actively tested, concept flows through implementation though
Debugging:
echo "<pre>";
var_dump(Test()); // Output: bool(true)
echo "<br><br>";
var_dump(Call_OverRides('OverRides','Test',"Parameter")); // Output: string(9) "Parameter"
Upvotes: 1
Reputation: 328
You may check http://php.net/manual/de/function.call-user-func.php from the PhP manual. It does not "overwrite" something, actually it just invokes your first function.
Upvotes: 1