class MyClass { public static $count = 0; public function __construct() { self::$count++; // accessing static property } } $obj1 = new MyClass(); $obj2 = new MyClass(); $obj3 = new MyClass(); echo MyClass::$count; // Output: 3
class MyClass { public static function hello() { echo "Hello, World!"; } } MyClass::hello(); // Output: Hello, World!
function addNumbers() { static $count = 0; $count++; echo $count; } addNumbers(); // Output: 1 addNumbers(); // Output: 2 addNumbers(); // Output: 3In this example, we defined a function called `addNumbers` that uses the static keyword to create a static variable called `$count`. Each time the function is called, the `$count` variable is incremented by 1 and then printed out. Package library used: Core PHP