class Counter { public static $count = 0; public static function increment() { self::$count++; } } Counter::increment(); // increments count to 1 Counter::increment(); // increments count to 2 echo Counter::$count; // prints out 2
use Carbon\Carbon; class Employee { public $name; public static $hiredAt; public function __construct($name) { $this->name = $name; static::$hiredAt = Carbon::now(); } } $employee1 = new Employee('John'); $employee2 = new Employee('Jane'); echo $employee1::$hiredAt->toDateTimeString(); // prints out current date and time echo $employee2::$hiredAt->toDateTimeString(); // also prints out current date and timeIn this example, the static field `$hiredAt` keeps track of the time an employee object is created. This is done by setting `$hiredAt` to the current date and time using the Carbon library. The Carbon library is used to manipulate dates and times in PHP. In conclusion, PHP static fields allows us to store data that is associated with a class and not with any specific instance of it. This can be useful for keeping track of data that is shared across all instances of a class. The examples provided demonstrate different use cases for static fields in PHP.