Can non-anonymous functions in PHP use the 'use' keyword?

Can non-anonymous functions in PHP use the 'use' keyword? Or it is available only for anonymous functions.

Can I write a php file like this

// L.php
// assume $_texts is in this context..

$_language = null;

function L_init($language) use (&$_language)
{
  $_language = $language;
}

function L($key) use ($_texts, $_language)
{
  $_texts[$_language][$key];
}

So another file can use it as follows

// client.php
require_once 'L.php';

L_init('en');
echo L('GREETING'); // Will output localize string of key 'GREETING'
+4
source share
2 answers

No, you can’t.

The code generates syntax errors.

-2
source

It is available for anonymous functions, but you can assign it to a variable:

$some_external_var = "World!";
$function = function() use($some_external_var){
    echo "Hello ".$some_external_var;
};

Finally, you can call it with:

call_user_func($function);

or simply:

$function();
+1
source

All Articles