I had some problems with this topic and I wrote a solution that I want to share with every one. By using a new ReflectionClass($objectOrClass)
, you can use the instance method getTraits()
. The problem is it will only returns an array of traits for the $objectOrClass
, and not the inherited traits from the traits or from the extended class.
Here is the solution :
/** @return ReflectionClass[] */
function get_reflection_class_traits( ReflectionClass $reflection, array $traits = [] ): array {
if ( $reflection->getParentClass() ) {
$traits = get_reflection_class_traits( $reflection->getParentClass(), $traits );
}
if ( ! empty( $reflection->getTraits() ) ) {
foreach ( $reflection->getTraits() as $trait_key => $trait ) {
$traits[$trait_key] = $trait;
$traits = get_reflection_class_traits( $trait, $traits );
}
}
return $traits;
}
// string|object $objectOrClass Either a string containing the name of the class to reflect, or an object.
$objectOrClass = //...
$reflection = new ReflectionClass( $objectOrClass );
$all_traits = $this->get_reflection_class_traits( $reflection );