What is the purpose of implementing a global logging functionality using a Singleton Pattern in PHP?

Implementing a global logging functionality using a Singleton Pattern in PHP allows for centralized logging across an application, making it easier to manage and track logs. By using a Singleton Pattern, we ensure that only one instance of the logger is created throughout the application, preventing unnecessary duplication of resources. This approach also promotes reusability and maintainability of the logging functionality.

class Logger
{
    private static $instance;
    private $logFile;

    private function __construct()
    {
        $this->logFile = fopen('log.txt', 'a');
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Logger();
        }
        return self::$instance;
    }

    public function log($message)
    {
        fwrite($this->logFile, '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL);
    }

    private function __clone()
    {
        // Prevent cloning of the instance
    }
}

// Example usage
$logger = Logger::getInstance();
$logger->log('This is a log message.');