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.clas s.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->doSomethingEls e ();
}
}
?>
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->doSomethingEls e ();
}
constantly?
Martin
Comment