Traits and Code Inclusion
Learn about traits, how they work, and how we can use multiple traits in classes.
We'll cover the following
PHP allows classes to inherit from only a single parent class, but sometimes it may be necessary to use code from more than one resource. In these cases, it is common to chain many parent classes together. However, this can get very complicated and it isn’t good practice to exceed an inheritance tree of three generations. Another common practice is to include the code that we want to share between the classes by using the include
or require
PHP built-in functions. This practice, however, is more of a workaround and not an actual solution.
To solve the above problem, traits can be used. Traits are a new feature that was introduced in PHP version 5.4. PHP 5.4 and onwards allow a class to get its code from as many traits as are required.
How do traits work?
Traits resemble classes in the sense that they group together code elements under a common name. The syntax to declare traits is as follows:
trait TraitName {
// The trait's code
}
In the example given below, a trait named Price
has a method changePriceByDollars()
that calculates the new price from the old price and the price change in dollars.
Get hands-on with 1400+ tech skills courses.