PHP

PHP: global variable example

<?php
$x = 5; // global scope
$y = 5; 
function myTest() {
	//global $x;

	echo "<pre>";
	print_r($GLOBALS);
	echo $GLOBALS['x'];
	echo $GLOBALS['y'];
	echo "</pre>";
  // using x inside this function will generate an error
  //echo "<p>Variable x inside function is:" . $x .". </p>";
} 
myTest();

echo "<p>Variable x outside function is: $x</p>";

/*A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
*/
?>

Leave a Reply

Your email address will not be published. Required fields are marked *