PHP trait_exists() Function
Last Updated :
02 Mar, 2021
PHP implements a way to reuse code called Traits. The trait_exists() function in PHP is an inbuilt function that is used to check whether a trait exists or not. This function accepts the traitname and autoload as parameters and returns true if trait exists, false if not, null in case of an error.
Syntax :
trait_exists ( string $traitname , bool $autoload = ? ) : bool
Parameters: This function accepts two parameters as mentioned above and described below.
- $traitname: This parameter contains the name of the trait.
- $autoload: This parameter is a boolean value that tells whether to autoload, if not already loaded.
Return Value:
- It returns true, if a trait exists.
- It returns false, if the trait does not exist.
- It returns null for any error encountered.
Example 1:
PHP
<?php
trait Programming
{
private static $instance ;
protected $temp ;
public static function Designing()
{
self:: $instance = new static ();
self:: $instance ->temp = get_called_class(). ' ' .__TRAIT__;
return self:: $instance ;
}
}
if ( trait_exists( 'Programming' ) )
{
class Initializing
{
use Programming;
public function text( $strParam )
{
return $this ->temp. $strParam ;
}
}
}
echo Initializing::Designing()->text( '!!!' );
?>
|
Output:
Initializing Programming!!!
Example 2:
PHP
<?php
class Base
{
public function callBase()
{
echo 'This is base function!' . "<br>" ;
}
}
trait myTrait {
public function callBase()
{
parent::callBase();
echo 'This is trait function!' . "<br>" ;
}
}
class myClass extends Base
{
use myTrait;
}
$myObject = new myClass();
$myObject ->callBase();
if (trait_exists( "myTrait" ))
{
echo "\n myTrait exists! \n" ;
}
else
{
echo "\n myTrait does not exists! \n" ;
}
?>
|
Output:
This is base function!
This is trait function!
myTrait exists!
Reference : https://www.php.net/manual/en/function.trait-exists.php
Share your thoughts in the comments
Please Login to comment...