Object-Oriented PHP

PHP Interfaces, Inheritance, and Traits

Compare PHP interfaces, class inheritance, and traits, and learn when each mechanism is useful.

PHP Interfaces, Inheritance, and Traits

PHP offers several mechanisms for sharing and defining behavior. Interfaces describe a contract, inheritance extends a class, and traits reuse methods across classes.

Interfaces Define Contracts

An interface declares methods that implementing classes must provide.

interface Logger
{
    public function log(string $message): void;
}

class FileLogger implements Logger
{
    public function log(string $message): void
    {
        // Write the message to a protected log file.
    }
}

Code that depends on the Logger interface can work with different logger implementations without depending on a specific class.

Inheritance Extends a Class

A class can extend one parent class. The child class inherits accessible behavior and can add or override methods.

class Animal
{
    public function move(): string
    {
        return "Moving";
    }
}

class Bird extends Animal
{
    public function fly(): string
    {
        return "Flying";
    }
}

Use inheritance when there is a genuine “is-a” relationship. Deep inheritance hierarchies can make behavior difficult to understand.

Traits Reuse Methods

Traits provide a way to reuse methods in multiple classes without creating a parent-child relationship.

trait HasTimestamp
{
    public function currentTimestamp(): string
    {
        return date(DATE_ATOM);
    }
}

class Article
{
    use HasTimestamp;
}

Traits should represent cohesive reusable behavior. Too many traits can make a class's behavior difficult to discover.

Choosing the Right Tool

Use interfaces to define contracts and support interchangeable implementations. Use inheritance for a meaningful specialization. Use traits for small, reusable behavior that does not represent a separate object relationship.

Conclusion

Interfaces, inheritance, and traits solve different design problems. Choosing deliberately helps PHP applications remain flexible without creating unnecessary complexity.

Share this page Help other developers discover this resource.