Can you store a function in a PHP array?

Viewed 61172

e.g.:

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

Is this possible? What's the best alternative?

6 Answers

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.

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

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(); } 
}
Related