PHP全局对象

I have a Singleton pattern Database object which I would like to declare once for use within the system. I have a main include file which serves up all of the separate class files and also makes some global variables.

Here's the include file:

<?php
// Main API. We want to include everything here and then make some Global Vars:
require_once('database.class.php');

// Create the DB here:
$database = Database::Singleton();

require_once('user.class.php');
require_once('settings.class.php');

// Start the session:
session_start();
?>

In theory, $database should be a global variable accessible by anything included thereafter (i.e. user.class.php and settings.class.php. However, when I try to call a method in the Database class from the User class as follows:

$result = $database->FetchObject($queryString);

I get the following error:

Fatal error: Call to a member function NumRows() on a non-object in C:\Program Files (x86)\EasyPHP-5.3.4.0\www\PC Estimating\classes\user.class.php on line 122

Is anyone able to help?

If you are trying to use the $database object from inside a method of a class, you must use the global keyword, so the $database variable is visible from the method :

class User {
    function myMethod() {
        global $database;

        // Work with $database

    }
}


For more informations, take a look at the Variable scope section of the manual.


Another (better) solution, considering you are use a singleton, would be to get that object from the singleton :

class User {
    function myMethod() {
        $database = Database::Singleton();

        // Work with $database

    }
}

What's the rest of your code? Specifically in user.class.php and settings.class.php. If you want to use $database in one of your class methods, you'll need to either include global $database; at the top of the method (this is bad, don't do it), or rely on the singleton behaviour and use $database = Database::Singleton(); again. If the singleton is correctly set up, this should refer to the same instance as you originally created.