Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class uses a trait in PHP?

Tags:

php

traits

Notice that a trait may use other traits, so the class may not be using that trait directly. And also the class may be inherited from a parent class who is the one uses the trait.

Is this a question that can be solved within several lines or I would have to do some loops?

like image 444
bijiDango Avatar asked Sep 14 '17 11:09

bijiDango


People also ask

What is trait class 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).

What is the difference between a class and a trait in PHP?

The main difference between the Traits and Interfaces in PHP is that the Traits define the actual implementation of each method within each class, so many classes implement the same interface but having different behavior, while traits are just chunks of code injected in a class in PHP.

Can traits be inherited PHP?

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 have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.


2 Answers

The class_uses() function will return an array containing the names of all traits used by that class, and will work by passing it a class name or an instance.... however, you'd need to "recurse" through the inheritance tree to get all traits used, and through each trait as well

EDIT

Note that stealz at op dot pl has provided an example function showing how to do this recursion in the comments section of the linked PHP Docs page

like image 117
Mark Baker Avatar answered Oct 08 '22 10:10

Mark Baker


If anyone has this problem while using the Laravel framework, that has a helper function called class_uses_recursive().

https://laravel.com/docs/8.x/helpers#method-class-uses-recursive

like image 42
Ken Avatar answered Oct 08 '22 09:10

Ken