1

Basically, I have a "user" class, part of which is like this:

class user{
    private $username;

    public function get_last_visit(){
        return $GLOBALS['db']->get(
            'users',
            'last_visit',
            'username' => $this->username
        );
    }
}

I need to call a method of the object "db" from inside the "user" class. Is using the above the best way to go about this? I've heard people say that using the $GLOBALS variable is bad practice.

1
  • Yes, it is frowned upon.
    – tereško
    Dec 2, 2013 at 18:15

2 Answers 2

1

What you want to read about is Dependency Injection which enables you to inject objects you need into the construction of your User objects like so.

# Your updated User class
class User {
    private $username;
    private $db

    public function __construct($db){
        $this->db = $db
    }

    public function get_last_visit(){
        return $this->db->get(
            'users',
            'last_visit',
            'username' => $this->username
        );
    }
}
# Instantiate your Database Wrapper
$db = new DatabaseWrapper();

# Instantiate your User object with the DatabaseWrapper injected
$john_doe = new User($db);

$john_doe->get_last_visit();
2
  • This would make it a new object though, wouldn't it? With my db object, I have a "query counter" which increments every time a query is executed, but if this is creating a new object, then I wouldn't be able to keep a count of the number of queries because there'd be two separate db objects.
    – user2953013
    Dec 2, 2013 at 20:39
  • This would indeed create a new instance of the DB Class. We hit a bad example here. You probably want to create a Singleton for the DB Class which you pass into the construction of your User Class. Check this out: stackoverflow.com/questions/130878/…
    – tim
    Dec 2, 2013 at 21:40
0

It is frowned upon because of the issue of scope. As you've no doubt experienced, variables inside your functions and classes do not interact directly with anything outside their respective areas. Otherwise you would have variables colliding all over the place. This is why Objects and Methods in general are replacing procedural code from yesteryear. It's much easier to keep track of what's going on in your program when you have to explicitly pass the data, instead of relying on various $GLOBALS.

I highly recommend you dependency inject your database pointers. This way you don't keep re-creating your connection and your classes and methods become agnostic as to how the connection came to be.

class user{
    private $username;
    /** @var stdClass */
    protected $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function get_last_visit(){
        return $this->db->get(
            'users',
            'last_visit',
            'username' => $this->username
        );
    }
}
$user = new user($db);