Php: the global keyword
Self-tutoring about PHP: the tutor mentions an idea about PHP global.
Consider the file
$var1=”hello”;
function f1(){
echo $var1;
}
f1(); //call f1
In the code above, with almost any programming language I know of, $var1 has value “hello” in the function f1. f1 can override it, but if not, then $var1 maintains its external, “global” value: “hello”.
With the version of PHP I use, however, the $var1 inside f1 is undefined. To make it take on the value of the external $var1, it needs to be declared in f1 as global:
$var1=”hello”;
function f1(){
global $var1;
echo $var1;
}
With the global $var1 declaration, a call to f1 will cause it to output “hello”.
Source:
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.