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

issue.super_global

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

Super global variable access

function foo () 
{
    $bar = $_POST['bar'];
}

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

While you'll still need to access its value somewhere, you should ideally encapsulate it in a class (thus having just one single place with direct access) instead of having several accesses spread throughout the code.

Write a wrapper class

class Request
{
    public function getParam ($name)
    {
        return $_POST[$name];
    }
}
 
class Foo
{
    private $request;
 
    public function __construct (Request $request)
    {
        $this->request = $request;
    }

    public function foo ($bar) 
    {
        echo $this->request->getParam('bar');
    }
}

$request = new Request ();
$foo = new Foo ($request)