Can you store a function in a PHP array?
The recommended way to do this is with an anonymous function:
$functions = [
'function1' => function ($echo) {
echo $echo;
}
];
If you want to store a function that has already been declared then you can simply refer to it by name as a string:
function do_echo($echo) {
echo $echo;
}
$functions = [
'function1' => 'do_echo'
];
In ancient versions of PHP (<5.3) anonymous functions are not supported and you may need to resort to using create_function
(deprecated since PHP 7.2):
$functions = array(
'function1' => create_function('$echo', 'echo $echo;')
);
All of these methods are listed in the documentation under the callable
pseudo-type.
Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func
/call_user_func_array
:
$functions['function1']('Hello world!');
call_user_func($functions['function1'], 'Hello world!');
Store functions as elements of an array php
As long as your PHP version is >= 5.3
you'll be able to harness anonymous functions and regular functions in your array:
function yourFunction($string){
echo $string . " : by reference";
};
$array = array(
'a' => function($string){
echo $string;
},
'b' => 'yourFunction',
);
You can use the call_user_func
or call_user_func_array
functions.
call_user_func($array['a'], 'I love things');
call_user_func($array['b'], 'I love things');
Or As @Andrew stated in the comments too, you could call it as the following:
$array['a']('I love things');
$array['b']('I love things');
If you'd like to read more about these callback methods, it's filed under the callback
pseudo-type documentation on PHP.net and it is well worth a read!
Store function inside an array
Anonymous functions cannot have a name:
$arrayFn[1] = function (){
echo "test";
};
$arrayFn[1](); // run it!
Is is possible to store a reference to an object method?
It is. You have to use an array, with two values: the class instance (or string of the class name if you are calling a static method) and the method name as a string. This is documented on the Callbacks Man page:
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Demo (Codepad):
<?php
class Something {
public function abc() {
echo 'called';
}
}
$some = new Something;
$meth = array($some, 'abc');
$meth(); // 'called'
Note this is also works with the built-ins that require callbacks (Codepad):
class Filter {
public function doFilter($value) {
return $value !== 3;
}
}
$filter = new Filter;
$test = array(1,2,3,4,5);
var_dump(array_filter($test, array($filter, 'doFilter'))); // 'array(1,2,4,5)'
And for static methods -- note the 'Filter'
instead of an instance of a class as the first element in the array (Codepad):
class Filter {
public static function doFilter($value) {
return $value !== 3;
}
}
$test = array(1,2,3,4,5);
var_dump(array_filter($test, array('Filter', 'doFilter'))); // 'array(1,2,4,5)'
// -------- or -----------
var_dump(array_filter($test, 'Filter::doFilter')); // As of PHP 5.2.3
Function as array value
You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.
<?php
$functions = array(
'regular' => 'strlen',
'class_function' => array('ClassName', 'functionName'),
'object_method' => array($object, 'methodName'),
'closure' => function($foo) {
return $foo;
},
);
// while this works
$functions['regular']();
// this doesn't
$functions['class_function']();
// to make this work across the board, you'll need either
call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
// or
call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
Define and execute function inside php array
Since closure is a function and it must be executed in order to get a response. Here's how you can execute and return a response
$c = 'awesome';
$array=array(
"a"=>'test2',
"b"=> 'test',
"c"=> call_user_func(function() use ($c) {
//do something
return $c;
})
);
var_dump($array);//array(3) { ["a"]=> string(5) "test2" ["b"]=> string(4) "test" ["c"]=> string(7) "awesome" }
PHP store an anonymous function in an array (class context)
It's funny that you are getting NULL — when I test your code, I get the expected result (i.e. not NULL).
Try the following code, maybe this could work: (if not, try upgrading your PHP version?)
// ----------------------------------------------------
// First try with a simple array, outside a class
// ----------------------------------------------------
$test_array = array(
"string" => "some string" ,
"function" => function() {
echo 'i am an anonymous function outside a Class';
}
);
var_dump($test_array);
// ----------------------------------------------------
// Now try in a Class context
// ----------------------------------------------------
class classContext {
public static $functions = array();
public function __construct() {
self::$functions += array(
"string" => "some string in classContext" ,
"function" => function() {
echo 'i am an anonymous function inside a Class';
}
);
}
}
class secondClass {
public function __construct() {
var_dump(classContext::$functions);
var_dump(classContext::$functions['function']);
}
}
new classContext;
new secondClass;
The result should be as follows:
array(2) {
["string"]=>
string(11) "some string"
["function"]=>
object(Closure)#1 (0) {}
}
array(2) {
["string"]=>
string(27) "some string in classContext"
["function"]=>
object(Closure)#3 (1) {
["this"]=> object(classContext)#2 (0) {}
}
}
object(Closure)#3 (1) {
["this"]=> object(classContext)#2 (0) {}
}
Related Topics
How to Get JavaScript Function Data into a PHP Variable
Utility of Http Header "Content-Type: Application/Force-Download" For Mobile
Insert - Number of Bind Variables Doesn't Match Number of Fields in Prepared Statement
Regular Expression Pattern to Match Url With or Without Http://Www
Notice: Array to String Conversion In
How to Check If a String Starts With a Specified String
Error: "Input Is Not Proper Utf-8, Indicate Encoding !" Using PHP'S Simplexml_Load_String
Using MySQLi Bind_Param With Date and Time Columns
How to Find the Dates Between Two Specified Date
PHP Pdo Prepared Statement - MySQL Like Query
How to Validate Google Recaptcha V3 on Server Side
How to Enable Curl in Wamp Server
How to Re-Index the Values of an Array in PHP
Passing Multiple Variables to Another Page in Url