This tool is currently proof-of-concept. Your feedback and evaluation is valuable in helping to improve it and ensure its reports are meaninful.

Please click here to complete a short survey to tell us what you think. It should take less than 5 minutes and help further this research project!


Detected issues

Issue Method Line number
Global/Static variables NA 12
Use of static methods processAttr 40


Click highlighted lines for details

<?php/* @description     Transformation Style Sheets - Revolutionising PHP templating    * * @author          Tom Butler                                             * * @copyright       2017 Tom Butler <> |                      * * @license  BSD License * * @version         1.2                                                             */namespace Transphporm\Parser;class CssToXpath {	private $specialChars = [Tokenizer::WHITESPACE, Tokenizer::DOT, Tokenizer::GREATER_THAN,		'~', Tokenizer::NUM_SIGN, Tokenizer::OPEN_SQUARE_BRACKET, Tokenizer::MULTIPLY];	private $translators = [];

Global variables

Note: A future update will differentiate between private static variables and public static or global variables as private static variables do not cause as much of a problem.


  • Hidden dependencies
  • Broken encapsulation
  • One component can accidentally overwrite data required by another component (action at a distance)
  • You can only every have one copy of the variable
  • Adding code requires knowing exactly what variables are already in use
  • When working in teams, name clashes can be easily introduced
  • Global state makes it difficult to reuse the code. E.g. having two files open at the same time would require writing the code twice, three times for three files, etc.


The identification of global variables as a bad practice dates as far back at least as far back as 1973[1] and are one of the most widespread and well known bad practices related to flexibility. This is likely due to being available in almost every programming language, ease of use and speed to learn. They also cause severe problems in code and it's very easy to get caught out by using them, even in a small application.

Global vairables are widely labelled "bad practice" and have been for some time, for example back in 1999 Kernighan wrote:

Avoid global variables; wherever possible it is better to pass references to all data through function arguments


And Hevery[3] states:

I hope that by now most developers agree that global state should be treated like GOTO.

This attitude is widespread and Sayfan[4] sums up the problem:

Whenever shared mutable state is involved, it is easy for components to step on each other's toes.

Although "global variables are bad" is a common thing to here, for novice developers it's not immediately obvious why this is. However, the reasons have been covered frequently by developers of varying prominence. While writing about desiging the Eiffel programming language, [5] stated several problems with global variables:

Since global variables are shared by different modules, they make each of these modules more difficult to understand separately, diminishing readability and hence hampering maintenance.

As global variables constitute a form of undercover dependency between modules, they are a major obstacle to software evolution, since they make it harder to modify a module without impacting others.

They are a major source of nasty errors. Through a global variable, an error in a module may propagate to many others. As a result, the manifestation of the error may be quite remote from its cause in the software architecture, making it very hard to trace down errors and correct them. This problem is particularly serious in environments where incorrect array references may pollute other data.

Action at a distance

This problem is commonly referred to as action at a distance and described by Hevery[6] as:

Spooky Action at a Distance is when we run one thing that we believe is isolated (since we did not pass any references in) but unexpected interactions and state changes happen in distant locations of the system which we did not tell the object about. This can only happen via global state.

Broken encapsulation

The biggest issue with global variables (even private static variables) is that they break encapsulation. A class no longer has its own state and one instance of a class can affect the state of another. Although private static variables are the by far the least worst type of global variables they should still be refactored out where possible.

> Encapsulation refers to the bundling of data with the methods that operate on that data

By making the data globally accessible, encapsulation has been lost. Any part of the program has access to the data and can modify it. Even when using private static variables, each instance no longer has control of its own sate.

Tight coupling

Global variables introduce tight coupling. In Object Oriented Programming an object should be self-contained[7][8]. If a class depends on a global (or static) variable, then moving the class to a different project requires defining the required global variables in the new project. Private static variables do not not introduce additional coupling.

Name Clashes

Global variables can introduce name clashes:

everywhere in the program, you would have to keep track of the names of all the variables declared anywhere else in the program, so that you didn't accidentally re-use one.


The problem of name clashes is magnified by the size of a team. If two people are working on a piece of software and both use global variables, it's possible they'll write some code using the same variable names. During execution this might cause the two peices of code to interfere with each other.


As a very crude example, imagine the following:

 function getUser($id) {
$connection Database::$connection;

$connection->query('SELET * FROM user ...')

This code assumes that Database::$connection has been set correctly and not overwritten. If any part of the application accidently runs the code Database::$connection = null; (or sets it to anything other than a database connection) then the code will fail. This is due to broken encapsulation and action and a distance.

Anything in the code is able to change the property and cause unexpected behaviour when further methods are called on the instance.

This can also happen with private static properties:

class FileReadWrite {
    private static 

    public function 
__construct(string $file) {
self::$fileName $file;

    public function 
read() {

    public function 
write(string $data) {

//Works as expected:

$file = new FileReadWrite('./one.txt');

//cause a problem

$file1 = new FileReadWrite('./one.txt');
$file2 = new FileReadWrite('./two.txt');


This causes a problem because there is a global variable storing the file name. Assuming a class requires only one value of a variable across the whole application always limits flexibility. There are occasionally practical reasons for this such as keeping track of and limiting the number of open files/connections but flexibility is always reduced. Even in these practical exceptions, it introduces a new issue of separation of concerns: Should the class be concerned with the number of open connections throughout the application or should that be managed at an application level rather than a class level?

Although this is a contrived example, the same kind of bugs can occur any time a static variable is used. If it's set by one instance and read by another then unexpected changes can cause bugs.

Further reading


  1. Wulf, W., Shaw, M. (1973) Global varaibles considered harmful. ACM SIGPLAN Notices , pp.28-34.
  2. Kernighan, B. (1999) The Practice of Programming ISBN: 978-0201615869. Addison Wesley.
  3. Hevery, M. (2008) Top 10 things which make your code hard to test [online]. Available from:
  4. Sayfan, M. (n.d.) Avoid Global Variables, Environment Variables, and Singletons [online]. Available from:
  5. Meyer, B. (1988) Bidding farewell to globals. JOOP(Journal of Object-Oriented Programming) , pp.73-77.
  6. Hevery, M. (2008) Brittle Global State & Singletons [online]. Available from:
  7. Yaiser, M. (2011) Object-oriented programming concepts: Objects and classes [online]. Available from:
  8. Caromel, D. (1993) Toward a method of object-oriented concurrent programming. Communications of the ACM , pp.90-102.
  9. Summit, S. (1997) Visibility and Lifetime (Global Variables, etc.) [online]. Available from:
private $functionSet; private $id; public function __construct(\Transphporm\FunctionSet $functionSet, $prefix = '', $id = null) { $this->id = $id; self::$instances[$this->id] = $this; $this->functionSet = $functionSet; $this->translators = [ Tokenizer::WHITESPACE => function($string) use ($prefix) { return '//' . $prefix . $string; }, Tokenizer::MULTIPLY => function () { return '*'; }, '' => function($string) use ($prefix) { return '/' . $prefix . $string; }, Tokenizer::GREATER_THAN => function($string) use ($prefix) { return '/' . $prefix . $string; }, Tokenizer::NUM_SIGN => function($string) { return '[@id=\'' . $string . '\']'; }, Tokenizer::DOT => function($string) { return '[contains(concat(\' \', normalize-space(@class), \' \'), \' ' . $string . ' \')]'; }, Tokenizer::OPEN_SQUARE_BRACKET => function($string) { return '[' .'php:function(\'\Transphporm\Parser\CssToXpath::processAttr\', \'' . base64_encode(serialize($string)) . '\', ., "' . $this->id . '")' . ']'; } ]; } private function createSelector() { $selector = new \stdclass; $selector->type = ''; $selector->string = ''; return $selector; } //XPath only allows registering of static functions... this is a hacky workaround for that

Static methods

Summary of issues

  • Tight Coupling
  • Hidden dependencies
  • Global state (if also using static variables)

Tight Coupling

Use of static methods always reduces flexibility by introducing tight coupling[1]. A static method tightly couples the calling code to the specific class the method exists in.

function totalAbs(double valuedouble value2) {
abs(value) + abs(value2);

Here, the method totalAbs has a dependency on the Math class and the .abs() method will always be called. Although for testing purposes this may not be a problem, the coupling reduces flexibility because the total method can only work with doubles/integers, as that's all the Math.abs() function can use. Although type coercion will allow the use of any primitive numeric type, these types have limitations. It's impossible to use another class such as BigInteger or a class for dealing with greater precision decimals or even alternative numbering systems such as Roman numerals.

The totalAbs function takes two doubles and converts them to their absolute values before adding them. This is inflexible because it only works with doubles. It's tied to doubles because that's what the Math.abs() static method requires. If, instead, using OOP an interface was created to handle any number that had this method:

 interface Numeric {
    public function 
abs(): Numeric;

It would then be possible to rewrite the totalAbs method to work with any kind of number:

 function totalAbs(Numeric valueNumeric value): Numeric {
value.abs() + value2.abs();

By removing the static method and using an instance method in its place the totalAbs method is now agnostic about the type of number it is dealing with. It could be called with any of the following (assuming they implement the Numeric interface)

totalAbs(new Integer(4), new Integer(-53));

totalAbs(new Double(34.4), new Integer(-2));

totalAbs(new BigInteger('123445454564765739878989343225778'), new Integer(2343));

totalAbs(new RomanNumeral('VII'), new RomanNumeral('CXV'));

Making the method reusable in a way that it wasn't when static methods were being used. By changing the static methods to instance methods, flexibility has been enhanced as the method can be used with any numeric type, not just numeric types that are supported by the Math.abs() method.

Broken encapsulation

Static methods also break encapsulation. Encapsulation is defined by Rogers[2] as:

the bundling of data with the methods that operate on that data

By passing the numeric value into the abs method, the data being operated on is being separated from the methods that operate on it, breaking encapsulation. Instead using num.abs() the data is encapsulated in the num instance and its type is not visible or relevant to the outside world. abs() will work on the data and work regardless of num's type, providing it implements the abs method.

This is a simple example, but applies to all static methods. Use of polymorphic instance methods that work on encapsulated data will always be more flexible than static method calls which can only ever deal with specific pre-defined types.

Further reading


The only exception to this rule is when a static method is used for object creation in place of the new keyword[3]. This is because the new keyword is already a static call. However, even here a non-static factory is often preferable for testing purposes[4][5].


  1. Popov, N. (2014) Don't be STUPID: GRASP SOLID! [online]. Available from:
  2. Rogers, P. (2001) Encapsulation is not information hiding [online]. Available from:
  3. Sonmez, J. (2010) Static Methods Will Shock You [online]. Available from:
  4. Hevery, M. (2008) Static Methods are Death to Testability [online]. Available from:
  5. Butler, T. (2013) Are Static Methods/Variables bad practice? [online]. Available from:
$attr = unserialize(base64_decode($attr)); $functionSet = self::$instances[$hash]->functionSet; $functionSet->setElement($element[0]); $attributes = []; foreach($element[0]->attributes as $name => $node) { $attributes[$name] = $node->nodeValue; } $parser = new \Transphporm\Parser\Value($functionSet, true); $return = $parser->parseTokens($attr, $attributes); return is_array($return[0]) || $return[0] === '' ? false : $return[0]; } public function cleanup() { unset(self::$instances[$this->id]); } //split the css into indivudal functions private function split($css) { $selectors = []; $selector = $this->createSelector(); $selectors[] = $selector; foreach ($css as $token) { if (in_array($token['type'], $this->specialChars)) { $selector = $this->createSelector(); $selector->type = $token['type']; $selectors[] = $selector; } if (isset($token['value'])) $selectors[count($selectors)-1]->string = $token['value']; } return $selectors; } public function getXpath($css) { $css = $this->removeSpacesFromDirectDecend($css)->splitOnToken(Tokenizer::COLON)[0]->trim(); $selectors = $this->split($css); $xpath = '/'; foreach ($selectors as $selector) { if (isset($this->translators[$selector->type])) $xpath .= $this->translators[$selector->type]($selector->string, $xpath); } $xpath = str_replace('/[', '/*[', $xpath); return $xpath; } private function removeSpacesFromDirectDecend($css) { $tokens = new Tokens; $split = $css->splitOnToken(Tokenizer::GREATER_THAN); $numSplits = count($split); if ($numSplits <= 1) return $css; for ($i = 0; $i < $numSplits; $i++) { $tokens->add($split[$i]->trim()); if (isset($split[$i+1])) $tokens->add(['type' => Tokenizer::GREATER_THAN]); } return $tokens; } public function getDepth($css) { $parts = $css->splitOnToken(Tokenizer::COLON); return count($this->split($parts[0])); } public function getPseudo($css) { $parts = $css->splitOnToken(Tokenizer::COLON); array_shift($parts); return $parts; }}