Created
April 16, 2015 23:22
-
-
Save typeon/f59f90a4d2c946c7cd88 to your computer and use it in GitHub Desktop.
php traits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| trait PrintFunctionality { | |
| public function myPrint() { echo 'Hello'; } | |
| } | |
| class MyClass { | |
| // Insert trait methods | |
| use PrintFunctionality; | |
| } | |
| $o = new MyClass(); | |
| $o->myPrint(); // "Hello" | |
| Single inheritance sometimes forces the developer to make a choice between code reuse | |
| and a conceptually clean class hierarchy. To achieve greater code reuse, methods can be | |
| moved near the root of the class hierarchy, but then classes start to have methods they | |
| do not need which reduces the understandability and maintainability of the code. On | |
| the other hand, enforcing conceptual cleanliness in the class hierarchy will often lead | |
| to code duplication, which may cause inconsistencies. Traits provide a way to avoid this | |
| shortcoming in single inheritance by enabling code reuse that is independent of the | |
| class hierarchy. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment