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.
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.
trait MyFirstTrait{
public function traitMethod1(){
// code to do something
}
}
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();
We hope this article will help you understand PHP traits better. For more PHP interview questions, do check our website Best Interview Questions today.