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;
?>
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With