1

I have a global variable like

<?PHP
function PrintVariable($str){
   global ${"check" . $str} = "some value";
   echo  $checkmap;    
}
 PrintVariable('map');

but I am getting this error:

Parse error: syntax error, unexpected '=', expecting ',' or ';' in C:\wamp\www\PHP\index.php on line 3

after removing the global from the code everything work fine but I have to create global at this function.

halfer
  • 19,471
  • 17
  • 87
  • 173
Mona Coder
  • 5,994
  • 17
  • 60
  • 118

2 Answers2

3

There is no combined "declare global and assign value" statement in php.
You'd have to do that in two steps, e.g.

<?php
function foo($str) {
    global ${"check" . $str};
    ${"check" . $str} = "some value";
}

foo('bar');
echo $checkbar;

...but what you really should do is: avoid globals.

VolkerK
  • 93,904
  • 19
  • 160
  • 225
3

With the "global" keyword, you can only reference a variable, not set the value of it.

Your code would be:

<?PHP
function PrintVariable($str){
   global ${"check" . $str};
   ${"check" . $str} = "some value";
   echo  $checkmap; // outputs: some value
}
PrintVariable('map');
echo  $checkmap; // outputs: some value

See:

http://php.net/language.variables.scope

Configuration class - Get configuration array from the function string argument

Community
  • 1
  • 1
ChrisJohns.me
  • 174
  • 2
  • 6