PHP in a nutshell: Classes, inheritance and interfaces
What this part is about
This article, and every remaining one in the series, is about object-oriented programming. You probably know classes from another programming language, so I am not going to explain what they are or what inheritance is — I will show how you work with them in PHP and where the language has its own ideas about OOP.
The biggest of those ideas are three things: constructor property promotion, which halves the length of
a class, late static binding, which is the difference between self and static, and traits —
a mechanism most languages simply do not have.
Classes, properties and constructors
The listing below shows every element of a class we can work with: a constant, a static property, a constructor and an ordinary method. The rest of the article goes through them one by one.
final class User{ public const ROLE_ADMIN = 'admin'; // class constant
public static int $count = 0; // static property
public function __construct( // constructor private string $name, // constructor property promotion (since PHP 8.0) protected ?int $age = null, public array $roles = [], ) { self::$count++; // self:: — a reference to a static property } // of the same class
public function getName(): string // an ordinary method { return $this->name; }}
$u = new User('Paweł', 30); // creating an instanceConstructor property promotion
Constructor property promotion is a mechanism in PHP where a visibility modifier placed in front of a constructor parameter automatically creates a property of that name and assigns the passed value to it. It is by far the most pleasant change PHP 8.0 brought. Both of the versions below do exactly the same thing — the first was the only option before, the second is available since PHP 8.0:
// before PHP 8.0final class User{ private string $name; protected ?int $age; public array $roles;
public function __construct(string $name, ?int $age = null, array $roles = []) { $this->name = $name; $this->age = $age; $this->roles = $roles; }}
// since PHP 8.0 — the same thing, just shorterfinal class User{ public function __construct( private string $name, protected ?int $age = null, public array $roles = [], ) {}}Instead of repeating the same variable name three times in the code — when defining the parameter, when declaring the property and when assigning its value — we define it once, as a constructor parameter. Use this by default — you only need the manual form when the assignment has to transform the value.
The body of the constructor works exactly as before — it runs after the promoted properties have been assigned.
Class constants
A class constant is declared with the const keyword: a named value defined once, at class level. Unlike
a static property, which anyone can overwrite while the program runs, a constant cannot be modified. It also
takes no $ in front of its name, and we read its value with :: — straight off the class, with no need to
create an instance.
class Order{ public const STATUS_NEW = 'new'; public const STATUS_PAID = 'paid';
final public const CURRENCY = 'PLN'; // final on a constant — since PHP 8.1 const int MAX_ITEMS = 100; // an explicit constant type — since PHP 8.3 // earlier the type could not be written out, // it followed from the value alone}
Order::STATUS_NEW; // access through ::, without an instance
$order = new Order();$order::STATUS_NEW; // through an instance as well, but it is the same single valuefinal on a constant blocks redefining it in a child class — without it a child can substitute its own value
under the same name, and the code reading the constant will not even notice. An explicit type, in turn, makes
sure that a child which does redefine the constant cannot change its type along the way.
The destructor
A destructor is the opposite of a constructor: the __destruct() method, which you never call yourself — PHP
does it for you once the object is no longer needed. The interesting part is when exactly that happens:
final class Session{ public function __construct(private string $id) { echo "opening {$this->id}\n"; }
public function __destruct() { echo "closing {$this->id}\n"; }}
$a = new Session('a');$b = new Session('b');
unset($a);echo "last line\n";
// opening a// opening b// closing a ← here, because unset() took away the last reference// last line// closing b ← only when the script shuts downThe whole rule is visible here: the destructor of $a ran immediately, because its reference count dropped to
zero, while the destructor of $b ran only after the last line. In practice destructors are used rarely,
precisely because that moment is hard to predict. Do not rely on one for releasing critical resources such as
open files or connections — an explicit close() method, called when you decide, is the safer option.
Dynamic class names
Creating a new instance does not have to go through a literal class name. A variable holding that name works just as well, and so does an expression that returns one:
$u = new User('Paweł'); // a literal — the class name written out
$class = User::class;$u = new $class('Paweł'); // a variable holding the class name
// any expression in parentheses — since PHP 8.0$u = new ($isAdmin ? Admin::class : User::class)('Paweł');This comes in handy with the factory pattern and in DI containers. Remember to use ::class rather than
hand-written strings, to avoid mistakes — as mentioned in
the first part.
Visibility
The same three modifiers we can come across in many other programming languages, applying equally to properties, methods and constants:
| Modifier | Accessible from |
|---|---|
public |
anywhere |
protected |
the class and its descendants |
private |
only the declaring class — not its descendants |
One thing works differently here from what intuition suggests:
final class Money{ public function __construct(private int $amount) {}
public function equals(Money $other): bool { // ✅ works — we can reach $amount of another object, // even though it is a private property return $this->amount === $other->amount; }}The private modifier limits access to the class, not to a particular object. Every object of a given
class therefore has access to the private properties and methods of all the other objects of that same class —
and that is what lets us write methods like equals() or compareTo() without creating getters for private
properties.
Making properties private is a design decision, not a security measure — the private properties of a class can be reached from the outside using
ReflectionProperty. The modifiers are only there to communicate the intent of the class author and to keep the public API small, without actually protecting the data.
Typed properties
Properties can be typed since PHP 7.4 — the type is then enforced on every assignment:
final class A{ public int $x;}
$a = new A();
$a->x = 5; // ✅ a value matching the type$a->x = 'text'; // TypeError: Cannot assign string to property A::$x of type intMore interesting is what happens when we assign nothing at all:
$a = new A();
isset($a->x); // falseecho $a->x; // Error: Typed property A::$x must not be accessed // before initializationA typed property with no default value sits in an uninitialised state, which is not the same thing as
null. It is a separate, third state: there is no value, and reading it throws an error instead of returning
null.
Usually this behaviour works in your favour — it catches a forgotten assignment straight away. You only need to know the state exists, because the error message can be misleading.
readonly
readonly marks a property that may be written exactly once — every further attempt ends in an error, inside
the class included:
final class User{ public function __construct( public readonly string $id, // assignable exactly ONCE ) {}}public readonly string $id; // ✅public readonly $id; // ❌ readonly REQUIRES a type declarationpublic readonly int $n = 5; // ❌ readonly cannot have a default valueWriting is only allowed from inside the declaring class — which is why readonly (since PHP 8.1) is in
practice almost always paired with constructor property promotion. Because the value can only be set once,
the property can be public and we do not have to create a getter for it.
Since PHP 8.2 readonly can be placed in front of a whole class, which makes all of its properties immutable.
We will come back to this in part ten, with value objects.
Static properties and methods
A static element belongs to the class rather than to a particular object: it is shared by the whole class and
all of its objects, and we reach it with the :: operator — by class name from the outside, and through
self:: from inside the class. A static method has no access to $this, because there is no instance of the
class for $this to refer to.
final class Config{ private static array $data = [];
public static function set(string $key, mixed $value): void { self::$data[$key] = $value; }}
Config::set('debug', true);Foo::method(); // calling a NON-static method statically: // an Error in PHP 8 (a deprecation warning in PHP 7)
array_map(static function ($x) { /* no $this */ }, $items);Static properties are global state in disguise: they are harder to test, their behaviour is harder to predict, and they cannot be swapped out in a test. The performance edge over creating an object is a micro-optimisation. Reach for dependency injection by default, and treat a singleton (a private
__constructplus a staticgetInstance()) as a last resort.
Late static binding
This is the part where PHP does something that has no equivalent in many languages. The mechanism I am about to show solves a concrete problem: a child class can redefine a constant or a static property inherited from the base class, but a method written in that base class will still read the base class’s own version — even when we call that method on the child class.
Both self and static let us refer to the static elements of a class — they differ only in which class they
point at. self points at the class the code was written in, so inside an inherited method that is still
the base class. static points at the class the method was called on:
class Model{ public const TABLE = 'models';
public static function table(): string { return static::TABLE; // the constant of the called class // return self::TABLE; // always the constant of class Model }
public static function name(): string { return static::class; // the name of the called class (since PHP 5.5) // return get_called_class(); // the same thing, the older way }}
final class User extends Model{ public const TABLE = 'users';}
User::table(); // 'users' — with self::TABLE it would be 'models'User::name(); // 'User'get_called_class() is a built-in PHP function that returns the name of the class a method was called on —
exactly what static points at. It arrived in PHP 5.3 together with late static binding, and since PHP 5.5 we
write the same thing more briefly as static::class. Do not confuse it with $obj::class, reading a class
name off an instance — that form only arrived in PHP 8.0.
The mechanism itself is called late static binding: static is resolved only at the moment of the call, while
self is resolved at compile time, because it follows directly from where the code sits.
It matters a great deal with the factory pattern, where the method creating the object is declared in the base class:
class Model{ public static function create(): static { return new static(); // an object of the class the method was called on // return new self(); // always an object of class Model }}
final class User extends Model {}
User::create(); // a User instance (with new static) // a Model instance (with new self)Without this mechanism every child class would have to write its own create(), because the inherited version
would always return an object of the base class. Thanks to static, a single method in the base class serves
all of the child classes — and the same mechanism is behind methods that return an object of the same class, so
that calls can be chained.
One more important detail about the whole mechanism. The class static points at is fixed at the moment of the
call, but not every call changes it. A call by class name or on an object sets it anew, whereas calls through
self::, parent:: and static:: pass it along unchanged. It is the second case that surprises people most
often, because self:: does not take us back to the base class at all:
class A{ public static function who(): string { return static::class; }
public static function viaStatic(): string { return static::who(); } public static function viaSelf(): string { return self::who(); } public static function viaName(): string { return A::who(); }}
final class B extends A {}
B::viaStatic(); // 'B'B::viaSelf(); // 'B' — self:: passes the called class along, it does not reset itB::viaName(); // 'A' — only a call by class name sets it anewInheritance and abstract classes
An abstract class is a class we cannot create an instance of: it serves to gather the code shared by its child
classes and to force them to fill in the missing methods. Methods marked with the abstract keyword have no
body, and alongside them the class can declare methods that do have one. Elements of such an abstract class,
the one we inherit from, are reached through parent:::
abstract class Shape{ public function __construct(protected string $name) {}
abstract public function area(): float; // no body — the child MUST implement it
public function describe(): string // concrete, shared { return sprintf('%s has an area of %.2f', $this->name, $this->area()); }}
final class Circle extends Shape{ public function __construct(private float $r) { parent::__construct('Circle'); }
public function area(): float { return M_PI * $this->r ** 2; }}
// new Shape('x'); // Error: Cannot instantiate abstract class ShapeRules worth keeping in mind:
- A class can extend only one class.
finalon a method blocks overriding, on a class — inheritance.- PHP does not call
parent::__construct()automatically. If the parent has a constructor, you have to call it yourself. - Call
parent::__construct()at the top of the child class constructor’s body. Called at the end, it will overwrite the values that constructor has already assigned to properties inherited from the parent class. - Overriding can only widen visibility:
protected → publicis allowed,public → protectedis not. privateproperties and methods are not inherited and cannot be overridden — the child class has its own, independent private methods and properties.abstractmethods cannot beprivate.
An important note — changing the name of a parameter in an overridden method will not throw an error, but it does break calls to that method with named arguments.
class Mailer{ public function send(string $to, string $subject): void {}}
final class QueuedMailer extends Mailer{ public function send(string $recipient, string $subject): void {} // renamed parameter}
$mailer = new QueuedMailer();
$mailer->send(to: 'a@example.com', subject: 'Hello');// Error: Unknown named parameter $toSo keep parameter names the same across the whole hierarchy — I wrote about this in the part on functions.
And one last important rule: a constructor does not have to be compatible with the constructor of the parent class. It can take a different number of parameters, with different names and different types — PHP does not check constructor compatibility at all.
abstract class Entity{ public function __construct(protected string $id) {}}
final class Invoice extends Entity{ public function __construct(private int $number, private float $total) // a different signature { parent::__construct("inv-{$number}"); }}For any other method, a signature change like this would end in an error.
The #[\Override] attribute
Since PHP 8.3 we have the #[\Override] attribute, which marks a method that is meant to override one from the
parent class. PHP then checks whether it really overrides something, and reports an error if it does not. This
protects us against a typo in the name, and against the case where the method disappears from the base class
while the child goes on “overriding” it.
class Repository{ public function findAll(): array { return []; }}
final class UserRepository extends Repository{ #[\Override] public function findAll(): array { return ['...']; } // ✅ really does override
#[\Override] public function findAl(): array { return []; } // a typo in the name — findAl() does not exist in the parent class, // so there is nothing to override: // Fatal error: UserRepository::findAl() has #[\Override] attribute, // but no matching parent method exists}Interfaces
An interface is a pure contract — a list of methods without bodies that the implementing class has to supply. Unlike inheritance, where we can only inherit from a single class, we can implement several interfaces:
interface Renderable{ const VERSION = '1.0'; // constants are allowed
// no body; works practically the same as public abstract in an abstract class public function render(): string;}
interface Cacheable{ public function cacheKey(): string;}
final class Widget implements Renderable, Cacheable // SEVERAL interfaces{ public function render(): string { return '<div/>'; } public function cacheKey(): string { return 'widget'; }}
$w = new Widget();$w instanceof Renderable; // true$w instanceof Cacheable; // true — the object satisfies both contracts at once
interface Both extends Renderable, Cacheable {} // an interface can extend several tooabstract class |
interface |
|
|---|---|---|
| Method bodies | ✅ | ❌ |
| Properties | ✅ | ❌ (constants only) |
| Constructor | ✅ | ❌ (technically allowed, but do not) |
| Visibility | any | public only |
| How many per class | ❌ one | ✅ several |
| Answers the question | “is something, with shared code” | “can do something, a contract” |
Declaring a constructor in an interface is syntactically allowed, but it is almost always a mistake: a constructor is an implementation detail, not part of the contract. An interface says what an object can do, not how it comes into being.
Programming to interfaces
When declaring a type in the signature of a method or a constructor, give the interface rather than a concrete class. That way any implementation can be swapped out without touching the code that uses it.
interface PaymentGateway{ public function charge(int $amount): bool;}
final class Stripe implements PaymentGateway{ public function charge(int $amount): bool { /* an API call */ return true; }}
final class FakeGateway implements PaymentGateway{ public function charge(int $amount): bool { return true; } // a stub for tests}
final class Checkout{ public function __construct(private PaymentGateway $gateway) {} // the interface, not a class}
new Checkout(new Stripe()); // in productionnew Checkout(new FakeGateway()); // in a testThe Checkout class does not know which implementation it is working with, and does not need to — all it needs
is that it has been handed something that can charge(). This is the same mechanism dependency injection
containers rest on: the configuration decides which implementation goes in place of the interface, and the rest
of the code is left untouched.
Traits
A trait is a code-reuse mechanism that works around the single-inheritance limitation: since a class can extend only one other class, we hand it ready-made methods and properties from traits. A trait is not a type — it cannot be used in a method signature — and its contents are pasted into the class at compile time, as if we had written them there by hand.
trait Loggable{ protected string $logLevel = 'info'; // traits CAN have properties abstract public function context(): array; // and abstract requirements
public function log(string $m): void { echo "[$this->logLevel] $m ", json_encode($this->context()), "\n"; }}
final class Order{ use Loggable;
public function __construct(private int $id) {}
public function context(): array { return ['order' => $this->id]; }}
(new Order(7))->log('saved'); // [info] saved {"order":7}Conflicts
When two traits define the same method, PHP will not choose for you — the conflict has to be resolved explicitly:
trait Polite { public function hello() { return 'Good morning'; } }trait Casual { public function hello() { return 'Hey'; } }
final class Greeter{ use Polite, Casual { Polite::hello insteadof Casual; // of the two versions, pick the one from Polite Casual::hello as casualHello; // expose the Casual version under another name Polite::hello as protected; // change the visibility of the chosen method }}Precedence
When the same method exists in the class, in a trait that class uses and in the base class, PHP reports no conflict — it quietly picks one of them:
class Base { public function hello() { return 'parent'; } }
trait Greet { public function hello() { return 'trait'; } }
class Child extends Base{ use Greet;
public function hello() { return 'class'; } // this one wins}The order is easy to remember: own beats trait, trait beats inherited. It is worth knowing, because a trait can quietly override a method from the base class with nothing in the class’s own code to signal it.
How a trait differs from inheritance
A trait looks like a base class pasted inside, but in several places it behaves differently from what that analogy suggests:
__CLASS__inside a trait returns the class that uses the trait, not the trait itself.- A static property of a trait is separate for every class that uses it. With inheritance it would be shared.
- A
finalmethod from a trait can still be overridden by the class that uses the trait. - A class using a trait with abstract methods does not have to be abstract itself, but it does have to implement those methods — otherwise we get a fatal error.
- Since PHP 8 a trait can declare
private abstractmethods — an abstract class cannot. - A property from a trait may be redeclared in the class only when it is fully compatible: the same visibility, the same type, the same default value.
Traits are essentially copy-paste carried out by the compiler. They create hidden dependencies, they cannot be swapped out or mocked in a test, and a look at a class’s signature does not tell you where a method came from. Prefer composition plus interfaces by default; keep traits for behaviour that is genuinely cross-cutting and stateless.
Anonymous classes
An anonymous class is a class declared where it is used: no name, straight after new. It can inherit,
implement interfaces and use traits like any other:
$logger = new class implements LoggerInterface { public function log(string $m): void { echo $m; }};
$x = new class(5) extends Base implements Foo { use SomeTrait;
public function __construct(private int $n) {}};They come in handy for one-off mocks in tests and for small adapters. It is worth knowing that every new class
inside a loop creates a new object of the same anonymous class — the class is compiled once.
What’s next
You now have the full set of tools for building type hierarchies. The next part is about how objects behave as
values: what == does exactly on objects, why clone is shallow and how to fix that, what the magic
methods are for — and what the hierarchy of exceptions and errors looks like in PHP 8.