This is a discussion on Using global within a class within the PHP Language forums, part of the PHP Programming Forums category; I have a class from within which other classes are called. In the constructor, I want to create an instance ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
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. <?php # 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: <?php # 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 {filename} 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 (); } constantly? Martin |
|
|||
|
Am Tue, 10 Aug 2004 18:11:35 +0100 schrieb Martin Lucas-Smith:
> > Normally I would use the standard $this-> system, but the problem is that > accessing the database could be several levels deep. > what kind of problem would that be? |
|
|||
|
Martin Lucas-Smith wrote:
> > > 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. > 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 |