← Back to PHP Course | Chapter 8: OOP | Lesson 9 of 14

PHP Traits

What are Traits?

A trait is a reusable block of methods that can be mixed into multiple, otherwise unrelated classes using the use keyword, solving the problem of sharing code between classes that don't share a common parent.

Example: What are Traits?

php
<?php
trait Greetable {
    function greet() {
        echo "Hello!";
    }
}
class User {
    use Greetable;
}
$user = new User();
$user->greet();
?>

Defining and Using Traits

Unlike inheritance, a trait doesn't establish an is-a relationship — it's purely a mechanism to copy in a set of method implementations, so a Loggable trait could be used by both a User class and an Order class with no relation to each other.

Example: Defining and Using Traits

php
<?php
trait Loggable {
    function log($msg) {
        echo "[LOG] $msg\n";
    }
}
class User {
    use Loggable;
}
class Order {
    use Loggable;
}
(new User())->log("User created");
(new Order())->log("Order placed");
?>

Multiple Traits

A class can use multiple traits at once, and PHP has specific conflict-resolution rules (insteadof and as) for cases where two traits it uses happen to define a method with the same name.

Example: Multiple Traits

php
<?php
trait A {
    function hello() { echo "A"; }
}
trait B {
    function hello() { echo "B"; }
}
class MyClass {
    use A, B {
        A::hello insteadof B;
    }
}
(new MyClass())->hello();
?>

Conflict Resolution (insteadof)

Traits can define abstract methods too, requiring the class that uses them to supply an implementation, which lets a trait depend on behavior it expects the host class to provide.

Example: Conflict Resolution (insteadof)

php
<?php
trait Shape {
    abstract function area();
    function describe() {
        echo "Area: " . $this->area();
    }
}
class Square {
    use Shape;
    function area() {
        return 16;
    }
}
(new Square())->describe();
?>

Trait Methods Visibility

Traits are a good fit for cross-cutting concerns like logging, timestamping, or serialization helpers that many otherwise-unrelated classes need, without forcing those classes into an artificial inheritance hierarchy.

Example: Trait Methods Visibility

php
<?php
trait Timestampable {
    function timestamp() {
        return date("Y-m-d");
    }
}
class Post {
    use Timestampable;
}
class Comment {
    use Timestampable;
}
echo (new Post())->timestamp();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.