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 } }
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).
A trait is similar to a class, but it is only for grouping methods in a fine-grained and consistent way. PHP does not allow you to create an instance of a Trait like an instance of a class. And there is no such concept of an instance of a trait.
In PHP, a trait is a way to enable developers to reuse methods of independent classes that exist in different inheritance hierarchies. Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.
Only classes can be extended. Traits are not classes.
To easily get the used traits you can call class_uses()
$usedTraits = class_uses(MyClass); // or $usedTraits = class_uses($myObject);
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 ) { //... }
You can write it yourself, by using the ReflectionClass
$rc = new ReflectionClass('myClass'); $count = count($rc->getTraits());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With