Can you store a function in a PHP array?

PhpArraysFunction

Php Problem Overview


e.g.:

$functions = array(
  'function1' => function($echo) { echo $echo; }
);

Is this possible? What's the best alternative?

Php Solutions


Solution 1 - Php

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!');

Solution 2 - Php

Since PHP "5.3.0 Anonymous functions become available", example of usage:

note that this is much faster than using old create_function...

//store anonymous function in an array variable e.g. $a["my_func"]
$a = array(
	"my_func" => function($param = "no parameter"){ 
		echo "In my function. Parameter: ".$param;
	}
);

//check if there is some function or method
if( is_callable( $a["my_func"] ) ) $a["my_func"](); 
	else echo "is not callable";
// OUTPUTS: "In my function. Parameter: no parameter"

echo "\n<br>"; //new line

if( is_callable( $a["my_func"] ) ) $a["my_func"]("Hi friend!"); 
	else echo "is not callable";
// OUTPUTS: "In my function. Parameter: Hi friend!"

echo "\n<br>"; //new line

if( is_callable( $a["somethingElse"] ) ) $a["somethingElse"]("Something else!"); 
	else echo "is not callable";
// OUTPUTS: "is not callable",(there is no function/method stored in $a["somethingElse"])

REFERENCES:

Solution 3 - Php

>Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

To follow up on Alex Barrett's post, create_function() returns a value that you can actually use to call the function, thusly:

$function = create_function('$echo', 'echo $echo;' );
$function('hello world');

Solution 4 - Php

Because I could...

Expanding on Alex Barrett's post.

I will be working on further refining this idea, maybe even to something like an external static class, possibly using the '...' token to allow variable length arguments.

In the following example I have used the keyword 'array' for clarity however square brackets would also be fine. The layout shown which employs an init function is intended to demonstrate organization for more complex code.

<?php
// works as per php 7.0.33

class pet {
    private $constructors;

    function __construct() {
    	$args = func_get_args();
	    $index = func_num_args()-1;
	    $this->init();
	
	    // Alex Barrett's suggested solution
	    // call_user_func($this->constructors[$index], $args);	
	
	    // RibaldEddie's way works also
	    $this->constructors[$index]($args);	
    }

    function init() {
	    $this->constructors = array(
		    function($args) { $this->__construct1($args[0]); },
		    function($args) { $this->__construct2($args[0], $args[1]); }
	    );
    }

    function __construct1($animal) {
	    echo 'Here is your new ' . $animal . '<br />';
    }

    function __construct2($firstName, $lastName) {
	    echo 'Name-<br />';
	    echo 'First: ' . $firstName . '<br />';
	    echo 'Last: ' . $lastName;
    }
}

$t = new pet('Cat');
echo '<br />';
$d = new pet('Oscar', 'Wilding');
?>

Ok, refined down to one line now as...

function __construct() {
    $this->{'__construct' . (func_num_args()-1)}(...func_get_args());
}

Can be used to overload any function, not just constructors.

Solution 5 - Php

Here is what worked for me

function debugPrint($value = 'll'){

	echo $value; 
}

$login = '';


$whoisit = array( "wifi" => 'a', "login" => 'debugPrint', "admin" => 'c' );
 
foreach ($whoisit as $key => $value) {
	 
	if(isset($$key)) {  
     // in this case login exists as a variable and I am using the value of login to store the function I want to call 
		$value(); } 
}

Solution 6 - Php

By using closure we can store a function in a array. Basically a closure is a function that can be created without a specified name - an anonymous function.

$a = 'function';
$array=array(
    "a"=> call_user_func(function() use ($a) {
        return $a;
    })
);
var_dump($array);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKirk OuimetView Question on Stackoverflow
Solution 1 - PhpAlex BarrettView Answer on Stackoverflow
Solution 2 - Phpjave.webView Answer on Stackoverflow
Solution 3 - PhpRibaldEddieView Answer on Stackoverflow
Solution 4 - PhpStuperfiedView Answer on Stackoverflow
Solution 5 - PhpFernando FischerView Answer on Stackoverflow
Solution 6 - Phpdhamo dharanView Answer on Stackoverflow