Skip to content
This repository was archived by the owner on Aug 29, 2023. It is now read-only.

issue.global

Edson Medina edited this page Jul 7, 2017 · 10 revisions

Global variables

function query ($sql) 
{
    global $db;
    return $db->doQuery ($sql);
}

Why is this a testing issue?

  • Global variables can be changed outside of the scope of your function, so its behavior is unpredictable in a running environment.
  • It would force your test to set globals, which could then affect subsequent tests that depend on the same globals.
  • Unit-tests should only test units in isolation. Having external (global) dependencies breaks that rule.

Possible refactorings

Pass the variable as an argument to your function

function query ($sql, $db)  

Pass the variable as a property (if you're dealing with a class)

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

    public function query ($sql) 
    {
        return $this->db->doQuery ($sql);
    }
}

Get it from some other source

$db = $this->dbFactory->getInstance();