PHP trait_exists() Function
The PHP trait_exists() function is used to check whether or not the given trait has been defined.
Syntax
trait_exists(trait, autoload)
Parameters
trait |
Required. Specify the trait name to check. The name is matched in a case-insensitive manner. |
autoload |
Optional. Specify whether to autoload if not already loaded. |
Return Value
Returns true if trait exists, false if not, null in case of an error.
Example: trait_exists() example
The example below shows the usage of trait_exists() function.
<?php trait World { private static $instance; protected $tmp; public static function World() { self::$instance = new static(); self::$instance->tmp = get_called_class().' '.__TRAIT__; return self::$instance; } } //checking that the trait exists //before trying to use it if (trait_exists('World')) { class Hello { use World; public function text($str) { return $this->tmp.$str; } } } echo Hello::World()->text('!'); ?>
The output of the above code will be:
Hello World!
❮ PHP Classes/Objects Reference