Using global within a class

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I have a class from within which other classes are called.

In the constructor, I want to create an instance of a database connection,
so that this database can be called elsewhere.

# Declare a class foo
class foo
     # Constructor
     function foo
         # Load the class file
         require_once ('database.class.php');

         # Create a database object
         $database = new database ();

     # Function to do work
     function doWork ()
         # Get the database object
         global $database;

         # Call some method from within bar
         echo $database->doSomethingElse ();

If I now create an instance of that object:

     # Create a foo
     $foo = new foo ();

     # Get foo to do stuff
     $foo->doWork ();

... this doesn't work. Instead, I get:

     Fatal error: Call to a member function doSomethingElse() on a
     non-object in on line {line number}

Basically the global isn't picking things up from the rest of the class.

Normally I would use the standard $this-> system, but the problem is that
accessing the database could be several levels deep.

Any idea how I can make use of a global variable without having to
continually pass the object between functions, i.e.

     function doWork ($database)
         echo $database->doSomethingElse ();



Re: Using global within a class

Am Tue, 10 Aug 2004 18:11:35 +0100 schrieb Martin Lucas-Smith:

Quoted text here. Click to load it

what kind of problem would that be?

Re: Using global within a class

Martin Lucas-Smith wrote:
Quoted text here. Click to load it

Variables in functions are destroyed when the function is finished. You
have to define your variable outside the class and do global $database;
everywhere you need it. It also might be interesting to (re)read the
part about scopes in the PHP Manual.

Pieter Nobels

Site Timeline