Artemis | Blog | Portfolio | About & Contact

2019 / 08 / 29 - PHP: Bad Idea / Good Idea (raw)

Global variables

Globals are variables defined on the top-level of PHP scripts.

They can be accessed from within a function by explicitly using global $var.

Bad idea: Using global variables and the global keyword

Using globals means that your entire code is tied to some top-level variables, which means that:

An usual example we see is the following.

<?php
$db = get_db();

function get_articles() {
    global $db;
    return $db->query("SELECT id, title, author FROM articles")
        ->fetchAll(PDO::FETCH_ASSOC);
}

$articles = get_articles();

Good idea: Using parameters, or even classes

Following the example below, the most direct change you can do is simply passing $db as a parameter.

The snippet in the previous example then becomes the following.

<?php
$db = get_db();

function get_articles($db_instance) {
    // Explicitly changed name to show difference between
    // the global $db and the local.
    return $db_instance->query("SELECT id, title, author FROM articles")
        ->fetchAll(PDO::FETCH_ASSOC);
}

$articles = get_articles($db);

However, in this example, we can clearly see that the function will always interact with an instance of our DB class.

That means that, since it works on a live variable, it can become a full class.

<?php
class ArticleRepository {
    public function __construct($db) {
        $this->db = $db;
    }

    public function get_articles() {
        return $this->db->query("SELECT id, title, author FROM articles")
            ->fetchAll(PDO::FETCH_ASSOC);
    }
}

$repo = new ArticleRepository(get_db());
$articles = $repo->get_articles();