Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get used traits in php-class?

Tags:

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   } } 
like image 451
Teson Avatar asked Nov 29 '12 19:11

Teson


People also ask

How traits are used in PHP?

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).

Can trait use trait PHP?

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.

What is trait in PHP with example?

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.

Can a trait extend a class PHP?

Only classes can be extended. Traits are not classes.


2 Answers

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 ) {      //... } 
like image 156
Maurice Avatar answered Nov 25 '22 05:11

Maurice


You can write it yourself, by using the ReflectionClass

$rc = new ReflectionClass('myClass'); $count = count($rc->getTraits()); 
like image 42
Ziumin Avatar answered Nov 25 '22 03:11

Ziumin