how to get used traits in php-class?

oop, php, traits

Solution

To easily get the used traits you can call class_uses()

$usedTraits = class_uses(MyClass);
// or
$usedTraits = class_uses($myObject);

General recommendations

When checking for available functionality, I would generally recommend to use `interfaces`. To add default functionality to an interface you would use `traits`. This way you can also benefit from type hinting.

Force an object having functionality by implementing an interface and then use a trait to implement default code for that interface.

class MyClass 
    implements SomeInterface 
{
    use SomeTrait;
}

Then you can check the interface by;

$myObject = new MyClass();
if ($myObject instanceof SomeInterface) {
    //...
}

And still use type hinting;

function someFunction( SomeInterface $object )
{ 
    //...
}

Problem

Is there any function in PHP (5.4) to get used traits as array or similar: ``` class myClass extends movingThings { use bikes, tanks; __construct() { echo 'I\'m using the two traits:' . ????; // bikes, tanks } } ```

Original source