Google News
logo
PHP Program to Test global scope (variable outside function)
Here's an example of a PHP program that tests global scope by declaring a variable outside a function and then accessing it inside the function :
Program :
<?php
	// This is a PHP program that tests global scope
	
	$globalVar = "Hello, World!"; // 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 :
Hello, World!
In this code, a global variable called `$globalVar` is declared outside of the `testScope()` function. The function then declares the same variable as global using the `global` keyword, which allows it to access the global variable from within the function.

Inside the function, the value of `$globalVar` is 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 "Hello, World!".

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.