What are Traits ? And how to use it in simple words ?
I agree ! Even though most of the programmer have deep knowledge of OOPs concept but they some time fail to explain the core concept of Few important terminology of OOPS.
I have made a small effort to explain one of such terms of OOPS which is Trait
— in simple words
“ Traits are something which helps you to reuse the certain portion of your code and prevents you from rewriting same code again and again”
I know its stupidity to explain such a big term in such a short definition .here we go in more depth:
Example :
Suppose You have 5 pages in your website where different stuffs are displaying ,now if you will be asked to set filter on all the pages for lets says color and price.
you have a list of products that you want to filter out based on above criteria (, color price ),So You can create a Filter trait that contains different functions for different filter types (Price,Color). You can then use this trait not only in your one class (as given in the example), but also in all other classes that need similar strategies .
coding example
Lets say my trait file name is filter_trait.php
trait filter{
public function color($category_id) {
echo $blue;
// you can return any result based on on your requirement
}
public function Price($category_id) {
echo $100;
// you can return any result based on on your requirement
}
}
}
=======================
Now the auspicious time has come to Use the above Trait
Having said that lets suppose you have 5 pages where you want to apply filter for color and price,one of the page is lets say category.php and its content is below
class allcategories{
use filter;
}
$o = new allcategories();
$o->Price();
$o->color();
Believe me no miracle is happening above , its a simple thing
i have accessed the function or methods of trait through object of class allcategories.because i wrote a line “use filter” in the class which give me right to access the methods of this trait “which is filter trait ”.
that’s it go ahead in all of your pages and just through the object of declared classes in those respective page use the methods of trait.
:)
DHANYABAAD/THANKS/SUKRIYA