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>
|
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>
|