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
}
}
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
}
}
I wish that will be useful (thanks to Maurice for interface usage):
To easily get the used traits you can call class_uses()
General recommendations
When checking for available functionality, I would generally recommend to use
interfaces
. To add default functionality to an interface you would usetraits
. 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.
Then you can check the interface by;
And still use type hinting;
You can write it yourself, by using the ReflectionClass
Just my 2 cents =)
Or with PHP > 5.6
class-uses(<class>)
will get the immediate traits of<class>
however it won't get all inherited traits by way of parent classes or traits of traits etc...If you need to get absolutely all inherited traits on a class I would recommend reading the comments in the official docs here:
http://php.net/manual/en/function.class-uses.php
class_uses
andReflectionClass->getTraits
will not work if you want to get traits from child class.Example.
I have this problem so I write simple code for get all traits from classes.