Skip to content

Chapter 2 of 7

Inheritance, Interfaces, and Traits

PHP supports inheritance through the extends keyword, which lets a child class reuse and extend the behavior of a parent class. The child inherits all public and protected properties and methods, and it can override them to specialize its behavior. This single-inheritance model is simple but limits a class to a single parent, which is why PHP offers complementary mechanisms for sharing code and contracts.

An interface defines a contract that classes promise to fulfill. It lists method signatures without providing their bodies, and any class that uses the implements keyword must supply concrete implementations for every method declared. PHP allows a class to implement multiple interfaces, separated by commas, giving you a form of multiple inheritance for behavior contracts without the ambiguities of inheriting from multiple classes at once. Interfaces are ideal for ensuring that unrelated classes expose a common set of methods, such as a Loggable requirement across various domain objects.

Traits solve a different problem: they let you reuse concrete method implementations across classes that do not share a parent. A trait is declared with the trait keyword and included in a class via the use statement, which mixes its methods into the class body. When two traits used in the same class define a method with the same name, PHP raises a fatal error unless you resolve the conflict explicitly using insteadof (to choose one trait's version) or as (to alias the method under a new name). Traits, interfaces, and inheritance together give PHP a flexible toolkit for code reuse while avoiding the pitfalls of traditional multiple inheritance.

All chapters
  1. 1Object-Oriented Foundations
  2. 2Inheritance, Interfaces, and Traits
  3. 3Namespaces and Dependency Management
  4. 4The PHP Type System
  5. 5Working with Arrays and Strings
  6. 6Databases, Sessions, and Error Handling
  7. 7Closures, Generators, and Magic Methods

Drill it

Reading is not remembering. These come from the Php Programming deck:

Q

What is a class in PHP OOP?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.class User { public string $na...

Q

What is the difference between public, protected, and private visibility in PHP?

public – accessible from anywhere.protected – accessible within the class and its subclasses.private – accessible only within the defining class.These are known...

Q

How do you create an object from a class in PHP?

Use the new keyword:$user = new User();This calls the class constructor (__construct) if one is defined.

Q

What is the purpose of the __construct() magic method?

__construct() is the constructor that runs automatically when an object is created with new.public function __construct(public string $name) {}It initializes ob...