316 of 410 menu

The trait_exists Function

The trait_exists function checks if the specified trait exists in the current scope. The first parameter is the trait name as a string, the second (optional) is a flag indicating whether to use autoloading.

Syntax

trait_exists(string $traitname, bool $autoload = true): bool

Example

Check if a trait exists:

<?php trait MyTrait { public function sayHello() { echo 'Hello'; } } $res = trait_exists('MyTrait'); var_dump($res); ?>

Code execution result:

true

Example

Check a non-existent trait with autoloading disabled:

<?php $res = trait_exists('NonExistentTrait', false); var_dump($res); ?>

Code execution result:

false

Example

Using the function in a conditional statement:

<?php if (trait_exists('Loggable')) { echo 'Trait exists'; } else { echo 'Trait does not exist'; } ?>

Code execution result (if the trait is not declared):

'Trait does not exist'

See Also

byenru