Before PHP 5.4, there was no way to implement multiple inheritance in PHP then PHP 5.4 introduce traits as a substitute of multiple inheritance in PHP.
By using the traits PHP solve the problem of Multiple Inheritance. A class only extend one class what if we wanted to use multiple classes method in a class ?
Problem of using multiple classes solved by TRAITS in PHP, it enables reuse of methods in several classes without any dependencies.
Syntax of traits:
<?php
trait name_of_trait{
// method goes here
}
As we can see it start with trait rather than a class keyword also we can not extend it like regular classes.
Example of Trait:
Using the above trait in a class
<?php
trait test{
public function mytest(){
$this->parentClassVarible=1; // we can change or access parent properties
$this->changeTrait();
}
public function changeTrait(){
// code goes here
}
}
If you are using class autoloader and composer then autoload will load the class otherwise you need to include the trait so Using the trait in class
<?php
include 'test.php';
class Test{
use test; // we can use namespace or include the trait file if it not loaded with //autoload
private $parentClassVarible=0;
public function testCls(){
//we can use trait methods here as well
$this->mytest();
}
}
We can also call outside of class a trait using parent class
$test= new Test();
$test->mytest(); // method if traits called using parent instance
We can not create object of a trait:
$testtrait = new test(); // it will generate error
Thanks for spending time to learn about traits in PHP, you can comment your thoughts and doubts in comment.
Implement multiple inheritance in php using traits
Let’s create a one more trait with name test2
<?php
trait test2{
public function anotherTest(){
$this->parentClassVarible=2; // we can change or access parent properties
}
}
Then using the both traits in class TestClass.php
<?php
include 'test.php';
include 'test2.php';
class Test{
use test,test2; // we can use namespace or include the trait file if it not loaded with //autoload
private $parentClassVarible=0;
public function testCls(){
//we can use trait methods here as well
$this->$parentClassVarible;
$this->mytest();
$this->anotherTest();
}
}
Output of above example:
0 2 1