PHP: How do I deal with GLOBALS?

Status
Not open for further replies.

montyauto

Banned
Jan 8, 2007
13
0
0
fastbuilder.eq19.com
Hi all,

I read in php manual:

Global variables: $GLOBALS
Note: $GLOBALS has been available since PHP 3.0.0.

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. You don't need to do a global $GLOBALS; to access it within functions or methods.

So If You don't need to do a global $GLOBALS, how to deal with this $GLOBALS so that the variable exist in function.

I made example below:

[code:1]<?php

$basic_url = 'http://www.php.net';

$GLOBALS = ..........;

function whatever() {

echo $GLOBALS.....;

}

whatever(); // would print 'http://www.php.net'

?>[/code:1]


How to deal with the $GLOBALS so the above script will produce 'http://www.php.net' without making a global $GLOBALS.

Please advise..
 


PHP:
<?php
function whatever($basic_url) {
      echo $basic_url;
}
whatever('http://www.php.net');
 
Taken literally, that documentation means:

Code:
<?php
$basic_url = 'http://www.php.net';
 
function whatever() {
  echo $GLOBALS['basic_url'];
}
 
whatever(); 
?>

This more readable approach also works:

Code:
<?php
$basic_url = 'http://www.php.net';
 
function whatever() {
  global $basic_url;
  echo $basic_url;
}
 
whatever(); 
?>

Using illusion's method of passing the variable works too.
 
Status
Not open for further replies.