Sometimes you may want to inherit from more than one class. Since this is not possible in PHP and other single inheritance languages like it, we have something called traits
.
To read more about inheritance in PHP, check out this shot.
trait
?In PHP, a trait
is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies.
Simply put, traits allow you to create desirable methods in a class setting, using the trait
keyword. You can then inherit this class through the use
keyword.
To create a trait
class:
<?php
trait TraitName {
// some code...
}
?>
To access a trait
class:
<?php
class MyNewClass {
use TraitName;
}
?
Let’s see the code below to understand better.
<?phpclass MainClass {public function greeting() {echo 'Good Day From MainClass'."\n";}}trait DesiredClass {public function welcome() {//parent::greeting();echo 'Welcome To Traits';}}class NewClass extends Mainclass {use DesiredClass;}$myObject = new NewClass();$myObject ->greeting();$myObject->welcome();/* You can uncomment line 10 while commenting out*line 20 and the result remains the same.*/?>
A base class was defined as MainClass
with a single method.
The trait class DesiredClass
was also created with another method.
The NewClass
that was created was able to access the method from both the base class and the trait class which we saw in its object $myobject
.
<?phptrait hello {public function message1() {echo "Nature is precious,\n";}}trait world{public function message2() {echo "So Let us unite to preserve it";}}class InUnity {use hello;}class WeCan {use hello, world;}$obj = new InUnity();$obj->message1();echo "****************\n";$obj2 = new WeCan();$obj2->message1();$obj2->message2();?>
Multiple traits can be created and used by one or more classes. The code above is an example of multiple trait inheritance.