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

php check if class is child of
check if object of class php
trait use in php
php trait vs class
php can a trait use another trait
php trait properties
php trait extends
class 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?

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

How to check if a class uses a trait in PHP?, Hack is a super set of PHP (and also a sub set, given some legacy stuff was removed), so most of the native functions can be used. With that  This function returns an array with the names of the traits that the given class uses. This does however not include any traits used by a parent class. This does however not include any traits used by a parent class.

Check your trait in a trait list:

$usingTrait = in_array( MyTrait::class, array_keys((new \ReflectionClass(MyClass::class))->getTraits()) );

This return true or false if MyClass uses MyTrait

Hack - how to check that an instance uses a Trait?, class_uses — Return the traits used by the given class This function returns an array with the names of the traits that the given class uses. check for string class names (as opposed to objects) to prevent the warning if the class is not found: The class uses the trait, and all the methods in the trait will be available in the class. If other classes need to use the msg1() function, simply use the message1 trait in those classes. This reduces code duplication, because there is no need to redeclare the same method over and over again.

Another way to approach this is to use interfaces that define what is expected of your traits. Then you are using "instanceof SomeInterface" instead of doing reflection or duck typing.

class_uses - Manual, traitname. Name of the trait to check. autoload. Whether to autoload if not already loaded. use World; Traits are compatible with class autoload mechanism - in fact, if you look at source code of trait_exists function, you will find similar peace  How to Use PHP Traits. PHP Traits are a great tool for code reuse. They allow developers to write methods that can be used in any number of classes, keeping your code DRY and more maintainable. Define a PHP Trait. Traits are defined much in the same way as classes.

The below function is from http://php.net/manual/en/function.class-uses.php, ulf's comment. Works perfect.

function class_uses_deep($class, $autoload = true)
{
    $traits = [];

    // Get traits of all parent classes
    do {
        $traits = array_merge(class_uses($class, $autoload), $traits);
    } while ($class = get_parent_class($class));

    // Get traits of all parent traits
    $traitsToSearch = $traits;
    while (!empty($traitsToSearch)) {
        $newTraits = class_uses(array_pop($traitsToSearch), $autoload);
        $traits = array_merge($newTraits, $traits);
        $traitsToSearch = array_merge($newTraits, $traitsToSearch);
    };

    foreach ($traits as $trait => $same) {
        $traits = array_merge(class_uses($trait, $autoload), $traits);
    }

    return array_unique($traits);
}

trait_exists - Manual, is_a — Checks if the object is of this class or has this class as one of its parents It took some time to find out how the last parameter should be used. Please  Class using trait. A class FooUsingBarTrait which uses a trait BarTrait to implement the aforementioned interface: <?php class FooUsingBarTrait implements BarInterface { use BarTrait; } Class not using trait. A class FooNotUsingBarTrait which does not use a trait BarTrait, but instead implements the aforementioned interface itself:

This is what I have in my Tools class

static function 
isTrait( $object, $traitName, $autoloader = true )
{
    $ret = class_uses( $object, $autoloader ) ;
    if( is_array( $ret ) )
    {
        $ret = array_search( $traitName, $ret ) !== false ;
    }
    return $ret ;
}

is_a - Manual, get_declared_traits — Returns an array of all declared traits class_uses() - Return the traits used by the given class; trait_exists() - Checks if the trait exists. Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

get_declared_traits - Manual, use Foo\Test; // means \Foo\Test - the initial \ is optional ?> On the other hand, "​use" for traits respects the current namespace: <?php namespace Foo\Bar; class​  A simple example of Multiple Traits and Composing Multiple Traits by which you can easily analyse you situation. A class can use multiple traits. The following example demonstrates how to use multiple traits in the IDE class. It simulates the C compilation model in PHP for the sake of demonstration.

Traits - Manual, <?php // Check that the class exists before trying to use it if (class_exists('​MyClass')) { $myclass = new MyClass(); } ?> Example #2 autoload parameter example. As of PHP 5.4.0, PHP implements a method of code reuse called Traits. Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

class_exists - Manual, Informally, whenever a trait is used by a class, the property and method to generate odd numbers given a generator of even numbers, and to test if a number is  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:

Comments
  • There are some functions that will return all traits used by a class (and its parents/etc) in the comments on this page: php.net/manual/en/function.class-uses.php
  • @iainn. I think ulf's shall do the work!
  • why not just class_uses instead of reflection?
  • $usingTrait = in_array(MyTrait::class, class_uses(MyClass::class))