开发者

access global variable as static class variable

开发者 https://www.devze.com 2022-12-11 16:09 出处:网络
Let\'s say I have the following class: class SQLMapper{ static find_user_by_id($id){ //sql l开发者_开发问答ogic here, using the $_DATABASE global to make a connection

Let's say I have the following class:

class SQLMapper{
    static find_user_by_id($id){
        //sql l开发者_开发问答ogic 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.


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' );
    }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消