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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?