PHP Static Class

PHP Static Class


  • A static PHP class is a specific implementation of the Singelton Design Pattern.
  • A static class variable can be accessed without instantiating the class first
  • This also means that there will only be one version of this variable.
  • A static method cannot access non-static variables and methods, since these require an instance of the class.
  • To access our static variable from our static class method, we prefix it with the self keyword ( works only inside the class )
  • From outside the class, we use the name of the class with double-colon operator

Code Sample

class PHPLogger{  
    public static  $loggerName = "Helmut's PHP-Logger:: ";
    public static $loggerLogLevel = 3;
    public static function getLogLevel() { return self::$loggerLogLevel; }
    public static function setLogLevel($level) { 
        self::$loggerLogLevel = $level; 
        echo self::$loggerName."Set New Logger Loglevel to: ". self::$loggerLogLevel."\n";
echo PHPLogger::$loggerName."Initial LogLevel: ". PHPLogger::getLogLevel() ."\n";
echo PHPLogger::$loggerName."New LogLevel: " . PHPLogger::getLogLevel()."\n";

Code Output

D:\xampp\htdocs\pvdata\wrapp\public_html\php> php logger.php

Helmut's PHP-Logger:: Initial LogLevel: 3
Helmut's PHP-Logger:: Set New Logger Loglevel to: 2
Helmut's PHP-Logger:: New LogLevel: 2