PHP 5.4 introduced a technique called traits. This technique aims to provide code re-usability functionality similar to mixins in other programming languages. The most common use case is to reuse methods among different classes.

Here is an example of the syntax;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
trait someMath
{
    function add($a, $b)
    {
        return $a + $b;
    }

    function multiply($a, $b)
    {
        return $a * $b;
    }
}

class Calculator
{
    use someMath;
}

$cal = new Calculator();
echo $cal->add(4, 6); // echoes 10

As you can see traits syntax is very similar to the syntax to create a class. We just need to change the keyword class for trait. Then we can apply the trait inside a class using the use keyword.

Precedence

Method collisions are resolved in this order of precedence:

  • Defined on the class
  • Defined on trait
  • Defined on parent class

The topmost in the list is the method that will be used when called from an instance. Lets see an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
trait someMath
{
    function add($a, $b)
    {
        return $a + $b;
    }

    function multiply($a, $b)
    {
        return $a * $b;
    }
}

class Calculator
{
    function subtract($a, $b)
    {
        return $a - $b;
    }

    function multiply($a, $b)
    {
        return $a * $b * 100;
    }
}

class BrokenCalculator extends Calculator
{
    use someMath;

    function add($a, $b)
    {
        return 9;
    }
}

$cal = new BrokenCalculator();
echo $cal->add(4, 6); // echoes 9
echo $cal->multiply(2, 2); // echoes 4
echo $cal->subtract(5, 3); // echoes 2

You can do a lot more cool things with traits, but there is no use on duplicating what is already well documented. You can see more use cases here: PHP Manual: Traits

[ design_patterns  php  programming  ]
Dependency injection (Inversion of Control) in Spring framework
Flyway - Version control for Databases in Java
Immutables and Java
Introduction to JDBI
Introduction to JDBC