Normally, you need to create an object (instantiate a class) to access its methods and properties. However, by using the **static** keyword, you can create members that belong to the class itself rather than any specific object. This means you can access them without creating an instance of the class.
Static methods can be called directly—without creating an instance of the class first. They are often used for utility functions or actions that don't depend on individual object data.
<?php
class Greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method using ClassName::methodName()
Greeting::welcome();
?>
::) is called the **Scope Resolution Operator**. It is used to access static, constant, and overridden members of a class.
Static properties belong to the class and are shared across all instances of that class. If you change a static property, it changes for every object created from that class.
<?php
class pi {
public static $value = 3.14159;
}
// Get static property
echo pi::$value;
?>
Inside a class, you cannot use $this to access static members because $this refers to an object instance. Instead, you use the self keyword followed by the scope resolution operator (::).
<?php
class Counter {
public static $count = 0;
public function __construct() {
self::$count++; // Increment static property on every new object
}
}
$a = new Counter();
$b = new Counter();
echo Counter::$count; // Outputs: 2
?>
MathUtils class).$object->member. Requires new.ClassName::member. Does NOT require new.$this).