Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
functions
traits
communitycreator

What is the PHP get_declared_traits() function?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

PHP has a single inheritance OOP structure. This implies that a subclass cannot inherit from multiple parent classes. We can use the traits command to overcome this challenge.

With the traits command, we can create classes with the desired methods, which we wish to have in our new class and is not part of its base class. In this shot, the goal is to see how we can get all the traits declared in a script, using an in-built PHP function: the get_declared_traits() function.

Note: To read more about traits in PHP, check out this shot.

What is the get_declared_traits() function?

The get_declared_traits() function returns an array of all the declared traits in the script where it is called.

Basic syntax

get_declared_traits();

Parameter

This function accepts no parameter.

Return value

This function returns an array with the names of all the declared traits in values, and null in the case of a failure.

Code

In the code snippet below, three traits are declared in the code and the get_declared_traits() function is called, which gets the name of all the traits that were declared in the script. The var_dump() function is used to print the output to the screen.

<?php
// creating a namespace, you can do without it.
namespace Example;
// Declare Trait
trait beginTrait
{
}
// another trait
trait midTrait
{
}
// and a third trait.
trait endTrait
{
}
// Get all traits declareds
$array = get_declared_traits();
var_dump($array);
?>

RELATED TAGS

php
functions
traits
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring