3

Let's say I have the following class:

class SQLMapper{
    static find_user_by_id($id){
        //sql logic here, using the $_DATABASE global to make a connection
    }
}

I could simply call:

global $_DATABASE;

at the top of my function, but I don't want to do that for ALL of my static methods. Is there a way to get a static variable inside my class to reference the global $_DATABASE array?

EDIT: I can't assign it in the constructor, since this is all static, and the constructor is never called.

1
  • Why does it all have to be static? Commented Nov 11, 2009 at 5:53

3 Answers 3

2

You can use the super-global array $_GLOBALS to access your $_DATABASE variable. For example:

query( $GLOBALS['_DATABASE'], 'some query' );

Alternatively, write a static function that returns the contents of that variable:

class SQLMapper
{
    static function getDatabase()
    {
        global $_DATABASE;
        return $_DATABASE;
    }

    static function find_user_by_id($id)
    {
        query( self::getDatabase(), 'some query' );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If it hurts, its likely that you're doing it wrong.

First off, without seeing more of your code its impossible to provide a more concrete solution, but I would strongly recommend that you consider rearranging your class structure so that your static functions (it sounds like you've got a long list of them to implement) become non-static.

In essence, you should consider accessing an instantiated instance of SQLMapper and then calling the appropriate method from the instance. Using this paradigm, you could just instantiate a class level property for $_DATABASE which can then be freely referenced by all methods in the class.

For example:

class SQLMapper {

    private $_db;

    public function __construct()
    {
        global $_DATABASE;

        $this->_db = $_DATABASE;
    }

    public function find_user_by_id($id) {

        $sql = "Select * from User WHERE Id = ?";

        $stmt = $this->_db->prepare($sql, $id);

        return $stmt->execute();
    }
}

With that said, using globals is generally a sign of poor code quality so I would also suggest that you consider taking a more object-oriented approach to your current design and look for tried and true methods for eliminating globals from your application altogether.

Comments

0

I'm not so sure I understand what you mean, sorry, but can you try using the static keyword?

1 Comment

This would make a better comment than answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.