What is PHP trait_exists() Function?
If you want to check whether a trait has been defined in your current script execution, use trait_exists() function.
Through trait, you can use same code in multiple classes without using inheritance. Through inheritance, a child class can inherit only one parent, but, by trait, a child class can inherit from multiple classes.
Syntax:
trait_exists(trait_name, autoload)
Parameters:
The Function has 1 required parameter and 1 optional parameter-
trait_name (Required): It specifies the class name.
autoload (Optional): It determines whether to call the autoloader if the original trait is not found. It can take 2 values-
- TRUE – it is the default value. It indicates that autoloader should be called if the original triat is not found.
- FALSE – It indicates that autoloader should not be called if the original trait is not found.
Return Values:
The function returns-
- TRUE – if the trait is defined.
- FALSE – if the trait is not defined.
- NULL – if there occurs any error.
Examples:
Example:
<?php
trait hello {}
if (trait_exists('hello')) {
echo "Trait 'hello' exists";
}else{
echo "Trait 'hello' doesn't exist";
}
echo "<br />";
trait welcome {}
if (trait_exists('welcome')) {
echo "Trait 'welcome' exists";
}else{
echo "Trait 'welcome' doesn't exist";
}
?>
Output:
Trait 'hello' exists
Trait 'welcome' exists
Practical Usages of trait_exists() Function:
The function is useful when working with libraries or frameworks.
PHP Version Support:
PHP 5 >= 5.0.2, PHP 7, PHP 8
Summary: PHP trait_exists() Function
trait_exists() is a class/object type function in PHP. Use this function before you need to use code from and trait and want to make sure that the trait exists.