Global Access

From within one function, you cannot by default access a variable defined in another function or elsewhere in the script. If you attempt to use a variable with the same name, you will only set or access a local variable.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$hello = "Hello";
$world = "World";

function Hello()
  {
  	echo $hello." ".$world;
  }
Hello();
?>
</p>
</body>
</html>

View the effect

If you want to access a global variable in a function, you have to explicitly say so. You use the global keyword. You will need to use the global keyword within every function that needs to access a particular named global variable. Be careful, though; if you change the value of the variable within the function, the value of the variable will be changed for the script as a whole.

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$hello = "Hello";
$world = "World";

function Hello()
  {
  	global $hello, $world;
  	echo $hello." ".$world;
  }
Hello();
?>
</p>
</body>
</html>

View the effect


Functions | What is a Function? | Defining a Function | Calling a Function | Passing Data | Variable Scope | Global Access | Setting Default Values for Arguments | Passing Arguments by Reference | Returning Values from Functions | Returning References from Functions | Static Variables | Creating Variable Functions | Creating Conditional Functions | Creating Functions within Functions | Include Files | Require Statement | Testing a Function | Type-Testing Functions | Handling Errors Returned by Functions
© 2008: Hann So
email: hso@voyager.deanza.edu