NYCPHP Meetup

NYPHP.org

[nycphp-talk] global variables

Hans Zaunere zaunere at yahoo.com
Thu May 22 18:55:26 EDT 2003


--- "Malcolm, Gary" <gmalcolm at professionalcredit.com> wrote:
> I've been told best practice is to NOT use globals in functions, if simply
> for readability but I bet we all do :) . Also, I wonder if a passed
> reference to a variable is as efficient... does anyone have an opinion on
> which of these is better and why (as a general rule)
> 1)
> 
> 	$var foo;
> 	function  bar(&$foo){
> 		do stuff to change $foo
> 	}
> 
> 2)
> 	var $foo = bar();
> 	function bar(){
> 		do stuff
> 		return a value for $foo
> 	}
> 
> 3)
> var $foo;
> bar();
> function bar(){
> 	global $foo;
> 	do stuff to change $foo
> }

>From various dealings and bugging people, I understand that this is
preferred:


function createAglobal() {
   $GLOBALS['myglobal'] = 'The Value';
}

/** Fast **/
function readAglobal() {
   echo "This is my global: {$GLOBALS['myglobal']}";
}

/** A *tiny* bit slower, but more readable if the global is used a lot **/
function readAglobal2() {
   $nochange = $GLOBALS['nochange'];

   echo "This is my global: $nochange";
}

function changeAglobal() {
   $GLOBALS['yeschange'] .= "Appending this string";
   echo "This changed the global var:  {$GLOBALS['yeschange']}";
}

function changeAglobal2() {
   $yeschange = &$GLOBALS['yeschange'];
   $yeschange .= "Appending this string";
   echo "This changed the global var:  $yeschange";
}

Or any variation thereof - YMMV  :)


H






More information about the talk mailing list