PHP class with a static property
13. Logger Class with Static LogCount
Write a class called 'Logger' with a static property called 'logCount' that keeps track of the number of log messages. Implement a static method to log a message.
Sample Solution:
PHP Code :
<?php
class Logger {
public static $logCount = 0;
public static function log($message) {
echo $message . "</br>";
self::$logCount++;
}
}
Logger::log("Log message 1");
Logger::log("Log message 2");
Logger::log("Log message 3");
echo "Total log count: " . Logger::$logCount . "</br>";
?>
Sample Output:
Log message 1 Log message 2 Log message 3 Total log count: 3
Explanation:
In the above exercise -
- The "Logger" class has a static property called $logCount, which is initially set to 0 and will be incremented each time a log message is logged.
- The log() method is a static method that takes a $message parameter and echoes the message. It also increments the logCount property using self::$logCount to refer to the static property.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP class Logger with a static property to count log messages and a static method that increments this counter and writes the log to a file.
- Write a PHP script to simulate multiple log entries using the Logger class and then output the final log count.
- Write a PHP function that uses the Logger class to log messages with a unique identifier and test concurrent logging.
- Write a PHP program to reset the Logger's static counter and verify the behavior across multiple instances of logging.
Go to:
PREV : Product Class with Comparable Interface.
NEXT : Math Class with Static Methods.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.