Jump to content

reach of variables


voodoochicken
 Share

Recommended Posts

hi, i wrote the following script (thats all the script, copy-paste)<?php$algo="una cadena asignada a algo";function prueba() { if (isset($algo)) { echo "definido "; } else { echo "no definido "; } echo $algo;}prueba();echo "fin";?>the output is 'no definido fin'it means the 'algo' var is not found inside the function. can anybody explain the reach of variables? i mean, if i can not find in a function the var i defined in the same script, not aslocal inside another function, how does the reach of variables work?tnx

Link to comment
Share on other sites

That is called variable scope. The variable $algo is defined as a global variable. If you want to access a global variable inside a function you need to tell the function you want to use the global version. You can either use the global keyword or the $GLOBALS array.

$algo="una cadena asignada a algo";function prueba() {  global $algo;  if (isset($algo)) {	echo "definido ";  } else {	echo "no definido ";  }  echo $GLOBALS['algo'];}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...