The PHP Global Statement
The global statement brings an outside variable "into" a function. In our previous tutorial, you learned that a variable created outside of a PHP function is not available to be used by that function. Usually you will get around this problem by passing an argument when you call the function.
function print_name($first_name) {echo "Hello $first_name";}
print_name("Susan Ann"); |
Another way to make an "outside" variable available to a function is to use the PHP global statement. The global statement brings the outside variable "into" the function. Let's take a look at the code.
$first_name = "Susan Ann";
function print_name( ) {global $first_name; echo "Hello $first_name";}
print_name( ); |
$first_name = "Susan Ann"; | This code will set the value of the $first_name variable to Susan Ann. This is not part of the function code.
function function_name( ) This tells the program that the following is a PHP function. print_name is the name of the function and is used to ID the function to the program. Although we are not passing any arguments to the function, we still need to follow the function name with parenthesis.
Inside the opening { and closing } is the code for the body of the function. . .
global $variable; This is the global statement that will make the value to the $first_name variable available to the function. As you can see, this statement ends with a semicolon.
echo "Hello $first_name"; | This line of code is the echo statement that will print Hello Susan Ann to the web browser.
This is the function call for the print_name function. As you can see, there is nothing inside the parenthesis. We do not need to pass an argument to the function because we are using the global statement.
|
|
This site needs an editor - click to learn more!
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map
Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact
BellaOnline Administration
for details.