PHP ยท Chapter 39 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  class Counter {
    public static $count = 0;
    static function increment() {
      self::$count++;
    }
  }
  Counter::increment();
  Counter::increment();
  echo Counter::$count;
?>
Output
2

self::$count refers to the static property shared by the whole class, not any single object.

Example 2 (php)
<?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();
?>
Output
12.56

Circle 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.
๐Ÿ’ก Note: Use abstract classes to enforce a shared structure across related classes while still allowing custom implementations.

๐Ÿ“ Quick Quiz

1. How do you access a static property from outside the class?

2. Can an abstract class be instantiated directly?

3. What must a child class do with an inherited abstract method?