Open In App

PHP trait_exists() Function

Last Updated : 02 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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
  
// Created trait Programming
trait Programming
{
    // Declared static instance
    private static $instance;
    protected $temp;
   
   // Defining static function in trait to Reuse
    public static function Designing()
    {
        self::$instance = new static();
        // Magic constant __TRAIT__ in PHP
        // It gets the class name for the static method called.
        self::$instance->temp = get_called_class().' '.__TRAIT__;
         
        return self::$instance;
    }
  
}
// Checking if 'Programming' Trait exists
if ( trait_exists( 'Programming' ) ) 
{
     
    class Initializing 
    {
        // Reusing trait 'Programming'
        use Programming;
  
        public function text( $strParam )
        {
            return $this->temp.$strParam;
        }
    }
  
}
  
echo Initializing::Designing()->text('!!!');
  
?>


Output:

Initializing Programming!!!

Example 2: 

PHP




<?php 
  
// Creating Base class
class Base 
{
    public function callBase()
     {
        echo 'This is base function!'."<br>";
     }
}
  
// Creating Trait
trait myTrait {
    public function callBase() 
    {
        parent::callBase();
         echo 'This is trait function!'."<br>";
    }
}
  
// Using myTrait
class myClass extends Base 
{
    use myTrait;
}
  
$myObject = new myClass();
$myObject->callBase();
  
// Checking if trait exists
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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads