3

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'm guessing it is impossible to do this, but might as well ask...)

3 Answers 3

5

You could do this...

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

CodePad.

Sign up to request clarification or add additional context in comments.

2 Comments

awesome, thanks. When it let's me accept an answer, I'll flip a coin between you and Tim. :)
I gave him an upvote, of course. Thanks to both of you, this solves the problem perfectly.
4

The closest I think you could get is by 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');
   }
}

1 Comment

2 seconds! +1 for the same idea as me :)
0

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

1 Comment

That won't be local to the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.