Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I once read that static classes are very difficult and even impossible to debug. Is this true and why?

I once read that static classes are very difficult and even impossible to debug. Is this true and why?

If an example would help, here is a PHP class I use to access a database (I don't think this is a PHP-specific question, though):

<?php

class DB
{
    private static $instance;

    private function __construct() { }

    public static function getInstance()
    {
        if(!self::$instance)
        {
            self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';', DB_USER, DB_PASS);
        }
        return self::$instance;
    }

    public static function getPreparedStatement($query)
    {
        $db = self::getInstance();
        return $db->prepare($query);
    }

    public static function query($query)
    {
        $stmt = self::getPreparedStatement($query);
        $stmt->execute();
    }

    public static function getResult($query)
    {
        $stmt = self::getPreparedStatement($query);
        $stmt->execute();
        return $stmt;
    }

    public static function getSingleRow($query)
    {
        $stmt = self::getPreparedStatement($query);
        $stmt->execute();
        return $stmt->fetch();
    }

    public static function getMultipleRows($query)
    {
        $stmt = self::getPreparedStatement($query);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

?>
like image 829
Mike Moore Avatar asked Aug 06 '10 13:08

Mike Moore


1 Answers

As long as your static class has methods and no data, it's just a namespace. No problem there. But if you have static data, you run into the same problems as global variables: you can no longer understand the behavior of the system from looking at local information. Particularly in a multi-threaded environment, you could be in for unexpected behavior and difficult debugging.

like image 123
John D. Cook Avatar answered Sep 29 '22 06:09

John D. Cook