Global access variable as a static class variable

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 just call:

global $_DATABASE;

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

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

+3
source share
3 answers

You can use a superglobal array $_GLOBALSto access your variable $_DATABASE. For example:

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

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

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

    static function find_user_by_id($id)
    {
        query( self::getDatabase(), 'some query' );
    }
}
+2
source

, , .

-, , , , (, ) .

, SQLMapper . , $_DATABASE, .

:

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

, , - .

+2

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

0
source

Source: https://habr.com/ru/post/1722545/


All Articles