What are traits in PHP?

A trait is a group of methods that you can reuse in many classes. It is a way to share code between classes that are not related, and it helps to solve the problem of no multiple inheritance in PHP.

You create a trait with the trait keyword and add it to a class using the use keyword.

<?php
trait Hello {
    public function sayHello() {
        echo "Hello ";
    }
}

trait World {
    public function sayWorld() {
        echo "World";
    }
}

class Greeting {
    use Hello, World;
}

$g = new Greeting();
$g->sayHello();
$g->sayWorld();
?>

Output:

Tutorials Class - Output Window

Hello World

  • A class can use many traits.
  • You can not create an object of a trait directly.
  • If two traits have a method with the same name, PHP gives an error. You can solve it with the insteadof keyword.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.