Php - extract an array into global variables

The extraction guide shows that you can extract an array, for example:

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

in $ one, $ two ...

But the extract function does not return variables. Is there a way to โ€œglobalizeโ€ these variables? Maybe not using extract, but a foreach loop?

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

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

A message will appear. The reason I do this is because users can change the language in which they view the website, so something like: ''. $ helloWorld. ''; will produce:

Hola Mundo!
+3
6

... : , (global).

$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>';

:

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>';

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>';

http://docs.php.net/gettext

+4
 $GLOBALS += $vars;

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

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

, , ? , ,

+4

extract() , .

, "", , , extract(), ( () , ).

+2

Do you mean:

 foreach($array as $var_name => $var_value)
 {
       global $$var_name;
       $$var_name = $var_value;
 }

It will be global every variable, and then set its value. For you it would create $oneand$two

+2
source
foreach ($array as $key => $value) {
  // initialize the variables as global
   global $$key;
   $$key = $value;
}

EDIT:

Just noticed my mistake, you will need to make the key to the variable array, which can be done by translating it into variable variables using the notation $$.

+1
source

Are you looking for variables that have been extracted? You can find them usingarray_keys()

0
source

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


All Articles