PHP - Inside 2d Array Function

I have a 2d array that includes an anonymous function that I would like to execute. For some reason, I am drawing a space on how to call the function.

The following fails:

$someArray[] = ['somevalue', function () {echo "test function";}];
$someArray[0][1]();

      

Mistake:

Notice: Undefined variable
Fatal error: Function name must be a string

      

If I do the following it works

$someFunc = $someArray[0][1];
$someFunc();

      

+3


source to share


2 answers


To call a function inside an array, use the following command:

call_user_func($someArray[0][1], $arg1, $arg2, $arg3);

      



Or that:

call_user_func_array($someArray[0][1], array($arg1, $arg2, $arg3));

      

+1


source


Before PHP 5.4, calling such a function does not work.

If you absolutely must do this, you will need to upgrade to PHP 5.4 or higher.



In older PHP versions, you have to dereference the closure (take it out of the array) before using it.

0


source







All Articles