PHP Static & Abstract
Static properties and methods belong to the class itself rather than to any specific object, and are accessed using the :: (scope resolution) operator without needing to create an instance.
An abstract class cannot be instantiated directly and may contain abstract methods โ methods declared without a body that must be implemented by any child class that extends it, enforcing a consistent structure.
static function myStatic() { }
abstract class Base {
abstract function doSomething();
}Static properties and methods
static $count = 0; and static function create() { } belong to the class, shared across all instances, and are accessed with ClassName::$count or ClassName::method().
Abstract classes and methods
abstract class Shape { abstract function area(); } declares that any concrete subclass must implement area(). The abstract class itself cannot be instantiated.
<?php
class Counter {
public static $count = 0;
static function increment() {
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count;
?>2self::$count refers to the static property shared by the whole class, not any single object.
<?php
abstract class Shape {
abstract function area();
}
class Circle extends Shape {
public $radius;
function __construct($r) { $this->radius = $r; }
function area() { return 3.14 * $this->radius ** 2; }
}
echo (new Circle(2))->area();
?>12.56Circle must implement area() because it extends the abstract Shape class.
Key points
- Static members belong to the class, not individual objects.
- self:: and ClassName:: access static members from within and outside the class.
- An abstract class cannot be instantiated directly.
- Abstract methods must be implemented by any concrete child class.
