Red-headed? Widow’s peak? Blue eyes?
Naw, not those kind of traits! As of PHP 5.4, the implementation of Traits has been added. In terms of object oriented programming, we know that the single-level inheritence restriction of PHP can be, well, limiting. However, this will allow for horizontal code-reuse by creation reusable sub-classes that can be implemented into your main class with precedence being given to the trait.
For example:
class Framework { public function doSayHello() { echo "Hello, "; } } trait SayHello { public function doSayHello() { parent::doSayHello(); echo "world!"; } } class HelloWorld extends Framework { use SayHello; } $myHello = new HelloWorld(); $myHello->doSayHello();
This would print, “Hello, world!”
If you’re new to PHP, this may seem a bit abstract or complex, but once you’ve worked with object-oriented code and experience first hand how unwieldy your classes can get, you’ll better understand their usefulness.
Happy PHP’ing!
Leave a Comment
You must be logged in to post a comment.