Google News
logo
PHP Program to Use the global keyword to access a global variable from within a function
Here's an example of a PHP program that uses the `global` keyword to access a global variable from within a function :
Program :
<?php
	// This is a PHP program that uses the global keyword to access a global variable from within a function
	
	$globalVar = "Welcome to Free Time Learn"; // A global variable
	
	function testScope() {
		global $globalVar; // Declare the global variable inside the function
		echo $globalVar; // Print the value of the global variable
	}
	
	testScope(); // Call the function to test the global variable
?>
Output :
Welcome to Free Time Learn
In this code, a global variable called `$globalVar` is declared outside of the `testScope()` function. Inside the function, the `global` keyword is used to declare the same variable as global, which allows it to access the global variable from within the function.

The value of `$globalVar` is then printed to the screen using the `echo` command. When the function is called at the end of the program, it outputs the value of the global variable "Welcome to Free Time Learn".

This demonstrates how global variables can be accessed from within functions in PHP by using the `global` keyword. However, it is generally recommended to avoid using global variables whenever possible, as they can make code more difficult to understand and maintain.