The class_uses() function is an inbuilt function in PHP where the traits utilized by the given class, will be returned.
Syntax:
class_uses($object_or_class,$autoload = true): array|false
Parameters: This function accepts the two parameters that are described below
- object_or_class: The name of the class or object passed in this parameter.
- autoload: This is an optional parameter for whether or not to automatically load the class file if it has not been loaded yet. The default is true.
Return value: If the function is successfully executed it will return an array otherwise it will return “false”.
Example 1: The following code demonstrates the class_uses() function.
PHP
<?php trait MyTrait { public function hello() { echo "Hello, world!\n" ; } } class MyClass { use MyTrait; } $traits = class_uses( "MyClass" ); echo "The following traits are used by MyClass:\n" ; foreach ( $traits as $trait ) { echo "- $trait\n" ; } ?> |
Output:
The following traits are used by MyClass: - MyTrait
Example 2: The following code demonstrates the class_uses() function.
PHP
<?php trait MyTrait1 { public function hello() { echo "Hello, world from Trait 1!\n" ; } } trait MyTrait2 { public function goodbye() { echo "Goodbye, world from Trait 2!\n" ; } } class MyClass { use MyTrait1, MyTrait2; } $traits = class_uses( "MyClass" ); echo "The following traits are used by MyClass:\n" ; foreach ( $traits as $trait ) { echo "- $trait\n" ; } ?> |
Output:
The following traits are used by MyClass: - MyTrait1 - MyTrait2
Reference: https://www.php.net/manual/en/function.class-uses.php