What is PHP get_declared_traits() Function?
If you want to see all the traits used in your current script, use PHP getÂ_declared_traits() function.
Through trait, you can use same code in multiple classes without using inheritance. Through inheritance, a child class can inherit only one parent, but, by trait, a child class can inherit from multiple classes.
Syntax:
get_declared_traits()
Parameters:
The Function has no parameter.
Return Values:
This function returns an indexed array whose each element is a trait name.
Examples:
Example:
<pre>
<?php
trait MyTrait{}
trait MySecondTrait{}
print_r(get_declared_traits());
?>
</pre>
Output:
Array
(
[0] => MyTrait
[1] => MySecondTrait
)
Notes on get_declared_traits() Function:
- When trait is used inside a namespace, the function returns the fully qualified name like namespace\trait. In PHP, Namespace is a mechanism to group related code elements (classes, interfaces, functions and constants) and it allows you to use same name for more than one class. See the example below-
<pre>
<?php
namespace MyNamespace;
trait MyTrait{}
print_r(get_declared_traits());
?>
</pre>
Output:
Array
(
[0] => MyNamespace\MyTrait
)
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP get_declared_interfaces() Function
get_declared_traits() is a class/object type function in PHP. Use this function to see list of traits used in a script.
Reference:
https://www.php.net/manual/en/function.get-declared-traits.php