Global Variables in PHP vs JavaScript

G

I’m still relatively new to PHP and the one thing that continues to trip me up is the use of global variables. I cut my programming teeth many years ago on languages like C and Visual Basic and more recently JavaScript, all of which handle global variables differently to PHP.

To highlight this difference, consider this simple JavaScript code:

Dummy Content
<script type='text/javascript'>
//<![CDATA[

	var foo = 'A';	// Global variable declaration.		
	
	function bar1() {
		document.write(foo + '<br />');	// --> 'A'. This is a global variable.
	}
	
	bar1();

//]]>
</script>

 

 

The variable foo is a global variable. It is persistent throughout the script and can be accessed by any function as is evident from the call to the function bar1() which will display A.

 

The equivalent code in PHP:

Dummy Content
<?php 

	$foo = 'A';	// Global variable declaration.	
	
	function bar1() {
		echo $foo . '<br />';	// --> nothing. This is a local variable.
		var_dump(isset($foo));	// --> bool(false)
	}
	
	bar1();
	
?>

 

 

Similar to it’s JavaScript counterpart, the variable $foo has global scope, but unlike the JavaScript version, the call to the function bar1() displays nothing. Why?

The reason is that within the scope of bar1() the variable $foo is assumed to be a local variable. A call to var_dump(isset($foo)) confirms that the variable $foo doesn’t exist within the bar1() function.

To ensure this PHP code is the functional equivalent of the JavaScript version, the variable $foo needs to be explicitly declared global within the function it is to be used, like so:

Dummy Content
<?php 

	$foo = 'A';	// Global variable declaration.	
	
	function bar2() {
		global $foo;
		echo $foo . '<br />';	// --> 'A'. This is a global variable.
	}
	
	bar2();
	
?>

 

 

About the author

A native Brit exiled in Japan, Steve spends too much of his time struggling with the Japanese language, dreaming of fish & chips and writing the occasional blog post he hopes others will find helpful.

Add comment

Steve

Recent Comments

Recent Posts