This is a bit of a weird problem, but say you’re trying to convert over to being all nice and OOP in your php code. Suddenly though, you notice some weird things. You can’t seem to access your global variables from within member functions!

For instance, say you have this include file called ‘names.php’ which has a huge global array in it called $names.

Attempt #1

in file names.php
$names = array(
  'bob', 'john', 'bobo', 'bobobobo'
);
require_once( 'names.php' );

class User
{
  private $name;
  function __construct()
  {
    $this->name = $names[ 0 ] ; # php can't access $names array,
    # even though its a global variable in 'names.php'!
  }
}

Attempt #2

require_once( 'names.php' );
global $names; # a good step, but still not enough

class User
{
  private $name;
  function __construct()
  {
    $this->name = $names[ 0 ] ; # php STILL can't access $names array,
    # even though its a global variable in 'names.php'!
  }
}

Attempt #3

require_once( 'names.php' );
global $names; # a good step, but still not enough

class User
{
  private $name;
  function __construct()
  {
    global $names; # the second piece of the puzzle.
    $this->name = $names[ 0 ] ; # ah, finally it works!
    # we had to have the global declaration in TWO places!
  }
}

In fact in PHP, the same goes for regular (non-object) functions as well. Need to declare global $variableName both after include AND inside function that uses the global.

One Comment

    • Jason
    • Posted October 22, 2008 at 11:53 am
    • Permalink

    *bump* (for people that don’t know and might come accross this)

    The global statement only needs to be used within the class/function so PHP knows it has to reference the variable from the outside (global) environment instead of within the class/function.

    require_once( ‘names.php’ );
    class User
    {
    private $name;
    function __construct()
    {
    global $names;
    $this->name = $names[ 0 ] ;
    }
    }


Post a Comment