Updated on 11 Aug 2019 | 3 Min Read
By
 

PHP aspects have always been a fascinating subject for developers as well as interviewers. Today, we will discuss a lot more than just an overview of PHP traits, which will extremely helpful for candidates preparing with PHP interview questions. As single heritance is a downside of PHP as a programming language, which means here a class can only inherit from another class, the introduction of traits in PHP version 5.4 has fixed this issue for developers to a certain level.

What is a Trait?

In PHP, a trait is a group of methods that developers desire to include within another class. This will prevent code duplication and a number of other benefits, which we will discuss ahead while avoiding the issues of multiple inheritances. Similar to an abstract, a trait can’t be instantiated on its own. To theoretically define it, Trait is a PHP mechanism promoting code reuse in single inheritance language. We have a huge set of crucial PHP technical interview questions with their suggested answers for your practice. This reduces the limitations of single inheritance by allowing developers method reusability independently in several independent classes present in various class hierarchies.

A simple trait example is mentioned below.

trait MyFirstTrait{
    public function traitMethod1(){
       // code to do something
    }
}

How to use Traits in PHP

class Base {
   public function sayHello() {
      echo 'Hello Gyes';
   }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'Hello World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();

Benefits of Using Traits

  • Reduces code duplication.
  • Prevents complex class inheritance that may non-sensible within the user application context.
  • Creation of simple, clear and concise traits to combine with functionality where required.

Drawbacks of Using Traits

  • Use of traits diverse from the single responsibility principle, which is crucial for some application built.
  • Due to logic duplication or source code and method conflicts, PHP traits are not capable to comply with all the methods of a class.

We hope this article will help you understand PHP traits better. For more PHP interview questions, do check our website Best Interview Questions today.