Traits, a sort of multiple inheretance
This afternoon, I was browsing the PHP Internals mailing list, and found something pretty interesting. It was a new proposal for some new OOP feature, called Traits. Traits is an language construct which enables you to reuse code more efficient.
It looks a bit like abstract classes, because of their syntax: almost the same as a class, only a different keyword, but you also can't create any instances of it. But why the hell would we need something like traits if we got abstract classes? Well to quote Stefan Marr, the proposer of this feature:
Quote from Stefan Marr
Code reuse is one of the main goals that object-oriented languages try to achieve
with inheritance. Unfortunately, single inheritance often forces the developer to take a decision in favor for either code reuse *or* conceptual clean class hierarchies. To achieve code reuse, methods have either to be duplicated or to be moved near the root of the class hierarchy, but this hampers
understandability and maintainability of code.
To circumvent this problems multiple inheritance and Mixins have been invented. But both of them are complex and hard to understand. PHP5 has been explicitly designed with the clean and successful model of Java in mind: single inheritance, but multiple interfaces. This decision has been taken
to avoid the known problems of for example C++. Traits have been invented to avoid those problems, too. They enable designer
to build conceptually clean class hierarchies without the need to consider code reuse or complexity problems, but focusing on the real problem domain and maintainability instead.
To view an example how traits will look like in a PHP script, click the read more link.
Here's an example using a trait, note that this example only shows how to use it, not the real benefits of it.
- <?php
- trait File
- {
- public function openFile($filename)
- {
- // Open the file here
- }
- public function write($data)
- {
- // write data
- }
- }
- abstract class BaseWriter
- {
- public abstract function generate_contents();
- }
- class XmlWriter extends BaseWriter
- {
- use File;
- public function generate_contents()
- {
- // Generate contents here
- $this -> openFile($this -> filename);
- $this -> write($data);
- }
- }
- class TextWriter extends BaseWriter
- {
- use File;
- public function generate_contents()
- {
- // generate it
- $this -> openFile($this -> filename);
- $this -> write($data);
- }
- }
The original RFC, and a lot more info can be found here:
http://marc.info/?l=php-internals&m=120336491008719&w=2

