Dave's Brain

Browse - programming tips - php global variables

Date: 2011jul15
Created: 2010mar27
Language: php

Q.  How do global variables work in PHP?

A.

Declare outside a function:

	$myglobal = 'http://www.example.com';

The you can use inside a function two ways:

Method one:
	function useGlobalVariable1() {
		global $myglobal;

		print "The global is $myglobal\n";
	}

Method two:

	function useGlobalVariable2() {
		$value = $GLOBALS['myglobal'];
		print "The global is $value\n";
	}

The first method is cleaner to me.
Just make sure you give your globals big names or possibly start with the
letter "g".

One advantage to the second method is that your global can begin undefined:

	function useGlobalVariableU() {
		if (!isset($GLOBALS['myglobal'])) {
			$GLOBALS['myglobal'] = slowFunction(); 
		}

		$value = $GLOBALS['myglobal'];
		print "The global is $value\n";
	}

In this cast you don't declare it outside the function.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.
Advertisements: