Menu
Coddy logo textTech

Traits vs Inheritance

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 55 of 91.

Now that you understand how traits work, let's clarify when to use traits versus inheritance. Both allow code reuse, but they serve different purposes and have distinct characteristics.

Inheritance establishes an "is-a" relationship. A Dog class extending Animal means a dog is an animal. The child class inherits the parent's identity and can be used anywhere the parent type is expected.

Traits provide a "has-a" capability. When a class uses a Loggable trait, it has logging functionality - but it doesn't become a logger. Traits add behavior without changing what the class fundamentally is.

<?php
// Inheritance: Dog IS an Animal
class Animal {
    public function breathe(): void {
        echo "Breathing";
    }
}

class Dog extends Animal {
    public function bark(): void {
        echo "Woof!";
    }
}

// Trait: Dog HAS logging capability
trait Loggable {
    public function log(string $msg): void {
        echo "Log: $msg";
    }
}

class Cat extends Animal {
    use Loggable;
}

Key differences to remember:

AspectInheritanceTraits
Relationshipis-ahas-a capability
LimitSingle parent onlyMultiple traits allowed
Type checkingWorks with instanceofNo type identity
Best forHierarchical relationshipsShared behaviors across unrelated classes

Use inheritance when classes share a common identity. Use traits when unrelated classes need the same functionality without being part of the same family tree.

challenge icon

Challenge

Easy

Let's build a vehicle system that demonstrates when to use inheritance versus traits. You'll create a hierarchy of vehicles that share a common identity through inheritance, while adding cross-cutting capabilities through traits.

You'll organize your code across four files:

  • Trackable.php — Create a trait called Trackable that provides GPS tracking capability. The trait should have:
    • A private property $location (string)
    • A method setLocation(string $location) that stores the current location
    • A method getLocation() that returns "Location: [location]"
    This trait represents a "has-a" capability — any vehicle can have tracking, but having tracking doesn't make something a vehicle.
  • Vehicle.php — Create a base Vehicle class that establishes the "is-a" relationship. Include the trait file. Use constructor promotion to define a protected $brand property. Add a method describe() that returns "Vehicle: [brand]". This class should use the Trackable trait since all vehicles in our fleet will have GPS.
  • Car.php — Create a Car class that extends Vehicle. Include the Vehicle file. Use constructor promotion to accept the brand and a private $doors (integer) property. Call the parent constructor with the brand. Override the describe() method to return "Car: [brand] with [doors] doors".
  • main.php — Include the Car file. You'll receive three inputs: a brand name, a number of doors, and a location string. Create a Car instance, set its location, then print two lines:
    • The result of calling describe()
    • The result of calling getLocation()

Notice how inheritance and traits work together here: Car is a Vehicle (inheritance establishes identity), while Vehicle has tracking capability (the trait adds behavior). You could use instanceof Vehicle to check if something is a vehicle, but there's no "Trackable" type to check against — that's the key difference between these two approaches.

Cheat sheet

Use inheritance for "is-a" relationships and traits for "has-a" capabilities.

Inheritance establishes identity - a child class is a type of parent class and can be used anywhere the parent type is expected.

Traits add behavior without changing class identity - a class has functionality but doesn't become that thing.

<?php
// Inheritance: Dog IS an Animal
class Animal {
    public function breathe(): void {
        echo "Breathing";
    }
}

class Dog extends Animal {
    public function bark(): void {
        echo "Woof!";
    }
}

// Trait: Cat HAS logging capability
trait Loggable {
    public function log(string $msg): void {
        echo "Log: $msg";
    }
}

class Cat extends Animal {
    use Loggable;
}
AspectInheritanceTraits
Relationshipis-ahas-a capability
LimitSingle parent onlyMultiple traits allowed
Type checkingWorks with instanceofNo type identity
Best forHierarchical relationshipsShared behaviors across unrelated classes

Use inheritance for hierarchical relationships where classes share common identity. Use traits for shared behaviors across unrelated classes.

Try it yourself

<?php
// Main file - create and test the Car instance

// TODO: Include the Car.php file

// Read inputs
$brand = trim(fgets(STDIN));
$doors = intval(trim(fgets(STDIN)));
$location = trim(fgets(STDIN));

// TODO: Create a Car instance with brand and doors

// TODO: Set the car's location

// TODO: Print the result of describe()

// TODO: Print the result of getLocation()
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming