Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create Global Variable Dynamically in PHP

Tags:

php

php-5.6

I need to create some global variable in PHP through function dynamically to be used out of function

I tried

<?php
function setthis(newglobal){
  global $_.newglobal._1;
  $_.newglobal._1 = "pampam";
}
setthis();

 echo $_newglobal_1;
?>

and I am getting this error

Line : 2, Error type : 4

Message : syntax error, unexpected ')', expecting '&' or variable (T_VARIABLE)

I also tried wrap them in quoted the variable like

<?php
function setthis(newglobal){
  global $_.'newglobal'._1;
  $_newglobal_1 = "pampam";
}
setthis();

 echo $_newglobal_1;
?>

an I am getting error Message

: syntax error, unexpected ')', expecting '&' or variable (T_VARIABLE)

can you please let me know if this is doable in PHP? or what I am doing wrong?

Update

<?php
function setthis($name){
    $GLOBALS[$name];
    $name = "pampam";
}
setthis();
echo $name;
?>
like image 557
Suffii Avatar asked Dec 07 '25 07:12

Suffii


2 Answers

Your error is always in the function header:

function setthis(newglobal){
               //^^^^^^^^^ needs a '$' in front of it

Then simply use the $GLOBALS array, e.g.

function setthis($name, $value = "pampam"){
    $GLOBALS[$name] = $value;
}
like image 61
Rizier123 Avatar answered Dec 08 '25 20:12

Rizier123


You can set dynamic variable names by using brackets:

$name = 'key';
${$name} = 'value';
echo $key; // Will echo 'value'

As described here: Dynamic variable names in PHP

Your code would look something like:

<?php

function setthis($global_key, $global_value){
  global ${"_" . $global_key . "_1"};

  ${"_" . $global_key . "_1"} = $global_value;
}

setthis('newglobal', 'pampam value');

echo $_newglobal_1; // Will echo 'pampam value'

?>

Or you may use PHP's GLOBALS array, which is available (globally):

<?php

function setthis($global_key, $global_value){
  $GLOBALS[ $global_key ] = $global_value;
}

setthis('newglobal', 'pampam value');

echo $GLOBALS['newglobal']; // Will echo 'pampam value'

?>

Info on all of these are in the PHP docs: http://php.net/manual/en/language.variables.scope.php

like image 41
ChrisJohns.me Avatar answered Dec 08 '25 20:12

ChrisJohns.me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!