Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Class/Object get_declared_traits() Function



The PHP Class/Object get_declared_traits() function is used to return an array of all the traits defined in the current script. Traits are a code reuse technique in single inheritance languages like PHP, allowing you to use functions from the trait from multiple classes.

Syntax

Below is the syntax of the PHP Class/Object get_declared_traits() function −

array get_declared_traits()

Parameters

This function does not take any parameters.

Return Value

The get_declared_traits() function returns an array with the names of all the defined traits in the current script.

PHP Version

First introduced in core PHP 5.4.0, the get_declared_traits() function continues to function easily in PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Class/Object get_declared_traits() function to get a list of declared traits.

<?php
   // define trait here
   trait ExampleTrait {}

   $traits = get_declared_traits();
   print_r($traits);
?>

Output

Here is the outcome of the following code −

Array
(
   [0] => ExampleTrait
)

Example 2

In the below PHP code we will use the get_declared_traits() function and declare multiple traits and retrieve them.

<?php
   // define traits here
   trait TraitOne {}
   trait TraitTwo {}
   
   $traits = get_declared_traits();
   print_r($traits);
?> 

Output

This will generate the below output −

Array
(
   [0] => TraitOne
   [1] => TraitTwo
)

Example 3

This example shows how traits with namespaces are listed. When using namespaces, get_declared_traits() function returns the traits' complete names, which include the namespace.

<?php
   // Define namespace here
   namespace MyNamespace {
      trait MyTrait {}
   }
  
   $traits = get_declared_traits();
   print_r($traits);
?> 

Output

This will create the below output −

Array
(
    [0] => MyNamespace\MyTrait
)
php_function_reference.htm
Advertisements