Google News
logo
PHP Program to Test local scope (variable inside function)
Here's an example of a PHP program that tests local scope by declaring a variable inside a function and then accessing it only within that function :
Program :
<?php
	// This is a PHP program that tests local scope
	
	function testScope() {
		$localVar = "Hello, World!"; // A local variable inside the function
		echo $localVar; // Print the value of the local variable
	}
	
	testScope(); // Call the function to test the local variable
	
	// Try to access the local variable outside the function
	// This will generate a "Undefined variable" error because the variable is only defined inside the function
	echo $localVar;
?>
Output :
Hello, World!
In this code, a function called `testScope()` is defined, and inside the function, a local variable called `$localVar` is declared and assigned the value "Hello, World!". The value of the local variable 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 local variable "Hello, World!".

However, when an attempt is made to access the local variable outside of the function, an "Undefined variable" error is generated, because the variable is only defined inside the function and cannot be accessed outside of it.

This demonstrates how local variables can only be accessed within the function in which they are defined, and not from outside that function. It is a good programming practice to limit the scope of variables as much as possible, as this helps to prevent naming conflicts and other errors.