Create a local variable in a call function from a string

I want to be able to call a function that will set one or more local variables in the calling function. For instance:

function someFunc () {
 loadTranslatedStrings($LOCALS, "spanish");
 echo $hello; // prints "hola";
 }

function loadTranslatedStrings (&$callerLocals, $lang) {
 if ($lang == 'spanish')
   $callerLocals['hello'] = 'hola';
 else if ($lang == 'french')
   $callerLocals['hello'] = 'bonjour';
 else
   $callerLocals['hello'] = 'hello';
 }

(I suppose this cannot be done, but may also ask ...)

+3
source share
3 answers

You can do it...

function someFunc () {
   loadTranslatedStrings($lang, "spanish");
   extract($lang); 
   echo $hello; // prints "hola";
}

CodePad .

+5
source

The closest thing I think you can get is using extract :

function someFunc()
{
   extract(loadStrings('french'));
   echo $hello;
}

function loadStrings($lang)
{
   switch($lang)
   {
      case 'spanish':
         return array('hello' => 'hola');
      case 'french':
         return array('hello' => 'bonjour');
   }
}
+4
source

You can do this using $GLOBALS:$GLOBALS['hello'] = 'hola';

0
source

Source: https://habr.com/ru/post/1795643/


All Articles