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();
}
}
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With