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

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

Example

Check if a trait exists:

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

Code execution result:

phptrue

Example

Check a non-existent trait with autoloading disabled:

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

Code execution result:

phpfalse

Example

Using the function in a conditional statement:

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

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

php'Trait does not exist'

See Also