In the last lesson we learnt about static method and properties. Today i am going to discuss about traits in php.
What is Traits ?
In PHP Traits are a mechanism of code inclusion or code re-usability. It is similar to (include, require). There might be a question striking in your mind that, we use inheritance for this purpose. Yes, you are thinking right. But there are some advantages of using traits over inheritance.
Since we know well that PHP supports only single inheritance means a class can only inherit a parent class only once. You can not inherit more than one classes in a child class.
While you can use more than one traits in a class. Let’s see how it works.
Declaration of Traits
we use trait
keyword for declaration as we do class
for class name declaration.
1 2 3 4 5 6 |
<?php // Declaration of trait trait NameOfTrait { // trait's code } ?> |
The below given example will demonstrate you how we use traits as code reuse and multiple code inclusion in place of inheritance. We have used priceConverter as trait name and method name changePrice.
We use keyword use
to inherit traits method and properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php // trait declaration trait priceConverter{ public function changePrice($dollar){ $this->dollar = $dollar; return $this->dollar * 70; } } // declaring class GoogleKnows class GoogleKnows{ // using trait use priceConverter; } $obj = new GoogleKnows(); $dollar = 3; echo $dollar." dollar converted in indian rupees = ".$obj->changePrice($dollar); ?> |
Output : 3 dollar converted in indian rupees = 210
In the above example we have used only one trait priceConverter
and as i told earlier that we can use more than one train in a class. So let’s take an example to prove this. In the below example i took two trait named country and priceConverter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php // First trait trait priceConverter{ public function changePrice($dollar){ $this->dollar = $dollar; return $this->dollar * 70; } } // Second trait trait country{ public function countryName($name){ return $this->name= $name; } } class GoogleKnows{ // used two trait use priceConverter; use country; } $obj = new GoogleKnows(); $dollar = 3; $country = 'India'; echo "Country name is ".$obj->countryName($country); echo "<br>"; echo $dollar." dollar converted in indian rupees = ".$obj->changePrice($dollar); ?> |
Output :
Country name is India
3 dollar converted in indian rupees = 210
Similarly you can use multiple traits as many you required,