Skip to content

Instantly share code, notes, and snippets.

@typeon
Created April 16, 2015 23:22
Show Gist options
  • Select an option

  • Save typeon/f59f90a4d2c946c7cd88 to your computer and use it in GitHub Desktop.

Select an option

Save typeon/f59f90a4d2c946c7cd88 to your computer and use it in GitHub Desktop.
php traits
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