What are traits in php ?
Traits solves the problem where php classes can't inhrerit behaviours or use properties, methods, etc from other classes except the parent class it extends to.
Traits in php makes a class have access to methods, properties in othe classes.
Let's use the bible story to elaborate this: We are not native isrealites so by default we as gentile class can't have any inheritance with the jews. But traits (Jesus Christ ) has come to bridge this gap. Take for example :
The child class, isrealites extends (inherits) from the parent class, God
class isrealites extends God { }
Gentile class (actually, Gentile Nation) wants to have access to the abrahamic promises but can't. Then Jesus Christ came in for us --Traits !
So create a trait class:
trait JesusChrist { public function salvationPromise() { echo "the promise is unto you and to your children, children"; } public function prosperityPromise() { echo "I will above all things that thou mayeth prosper even as thy soul prospereth "; } public function freedomFromSin() { echo "If the son shall make you free, you shall be free indeed"; } }
For gentiles to use this trait as well inherit all the promises, we provide a "Jesus Trait" for them.
// .... class Gentiles { use JesusChrist; } $gentile = new Gentiles(); //pick one promise echo $gentile-> freedomFromSin();
A full code will look like this:
trait JesusChrist { public function salvationPromise() { echo "the promise is unto you and to your children, children"; } public function prosperityPromise() { echo "I will above all things that thou mayeth prosper even as thy soul prospereth "; } public function freedomFromSin() { echo "If the son shall make you free, you shall be free indeed"; } } class Gentiles { use JesusChrist; } $gentile = new Gentiles(); //pick one promise echo $gentile-> freedomFromSin();
Traits are used to access methods and properties that extend the capabilities of a class.
More resources to learn from PHP DOC
Top comments (2)
Very nice.
Thank you so much for reading