Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - extract array into global variables

The manual on "extract" shows you can extract an array like:

extract(array('one'=>1,'two'=>2));

into $one,$two...

But the extract function doesn't return the variables. Is there a way to 'globalize' these variables? Maybe not using extract, but a foreach loop?

EDIT: (explanation about what I'm trying to achieve) I have an array containing hundreds of output messages which I want to have accessible as variables efficiently. What I mean is that whenever I want to output a message, say:

$englishMessages = array('helloWorld'=>'Hello World');
$spanishMessages = array('helloWorld'=>'Hola Mundo');
'<span id="some">'. $helloWorld .'</span>';

The message would appear. The reason I'm doing it like this is so that users can change the language they're viewing the website in, so something like: ''. $helloWorld .''; would produce:

Hola Mundo!
like image 969
Gal Avatar asked Dec 09 '22 17:12

Gal


2 Answers

 $GLOBALS += $vars;

for example

function foo() {
  $vars = array('aa' => 11, 'bb' => 22);
  $GLOBALS += $vars;
}

foo();
echo $aa; // prints 11

that said, can you explain why you need this? Using global variables is considered poor style, maybe there's a better way

like image 103
user187291 Avatar answered Dec 24 '22 23:12

user187291


Not exactly an answer to your question ...but: Keep the array, don't pollute the (global) variable namespace.

$englishMessages = array('helloWorld'=>'Hello World');
$spanishMessages = array('helloWorld'=>'Hola Mundo');

// wrap this in a nice function/method
$lang = $englishMessages;
// then use $lang for the output
'<span id="some">'. $lang['helloWorld'] .'</span>';

Some variations on the same theme:

function getMessages($language) {
  static $l = array(
    'en'=> array('helloWorld'=>'Hello World'),
    'es' => array('helloWorld'=>'Hola Mundo')
  );
  // <-- add handling reporting here -->
  return $l[$language];
}

$lang = getMessages('en');
echo '<span id="some">'. $lang['helloWorld'] .'</span>';

or

function __($language, $id) {
  static $l = array(
    'en'=> array('helloWorld'=>'Hello World'),
    'es' => array('helloWorld'=>'Hola Mundo')
  );
  // <-- add error handling here -->
  return $l[$language][$id];
}

echo '<span id="some">'. __('es', 'helloWorld') .'</span>';

You might also be interested in http://docs.php.net/gettext

like image 30
VolkerK Avatar answered Dec 24 '22 22:12

VolkerK