joshmac 0 Light Poster

I have a singleton class that I am revamping and need a little help with. I want to use the following syntax for my queries without having to declare a global object. Below is my current code:

   /**
     * The db database object
     *
     * @access private
     * @var object
     */
    private $db;

    /**
     * MySQLi database object
     *
     * @access private
     * @var object
     */
    private static $instance;

    /**
     * Current result set
     *
     * @access private
     * @var object
     */
    private $result;

    /**
     * The last result (processed)
     *
     * @access private
     * @var array
     */
    private $last_result;

    /**
     * The number of rows from last result
     *
     * @access private
     * @var int
     */
    private $row_count;

    /**
     * Last error
     *
     * @access private
     * @var string
     */
    private $last_error;

    /**
     * PHP5 Constructor
     *
     * Making this function 'private' blocks this class from being directly created.
     *
     * @access private

     */
    private function __construct() { }

    /**
     * Creates and references the db object.
     *
     * @access public
     * @return object MySQLi database object
     */
    public static function instance() {
        if ( !self::$instance )
            self::$instance = new db();
        return self::$instance;
    }

    /**
     * Connect to the MySQL database.
     *
     * @param string $host MySQL hostname
     * @param string $user MySQL username
     * @param string $password MySQL password
     * @param string $name MySQL database name
     * @return bool True if successful, false on error.
     */
    public function connection($host, $user, $password, $name) {
        // Connect to the database
        $this->db = new mysqli($host, $user, $password, $name);
        // Check connection
        if ( mysqli_connect_errno() ) {
            $this->last_error = mysqli_connect_error();
            return false;
        }
        return true;
    }

    public function query($sql) {
        $this->result = $this->db->query($sql);
        return $this->result;
    }

So then, what would I need to change in my class so that I will not have to declare a global variable for other classes and functions to use like db::query->();? Thanks in advance for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.