English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP tutorial

Advanced PHP tutorial

PHP & MySQL

PHP reference manual

PHP trait_exists() function usage and example

PHP Class/Object function reference manual

The trait_exists() function checks if the specified trait exists.

Syntax

trait_exists (string $traitname [, bool $autoload ] )

Definition and usage

Check if the specified traitname exists.

Parameter

Serial numberParameters and descriptions
1

traitname (required)

The name of the trait to be checked.

2

autoload (optional)

Whether to use automatic loading (autoload) if not loaded.

Return value

If the trait exists, it returns TRUE; if it does not exist, it returns FALSE. Returns NULL when an error occurs.

Online example

The following is the usage of this 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;
    }
}
if ( trait_exists( 'World' ) ) {
   
    class Hello {
        use World;
        public function text( $str )
        {
            return $this->tmp.$str;
        }
    }
}
echo Hello::World();->text('!!!'); // Hello World!!!
?>
Test and see ‹/›

Output result:

Hello World!!!

PHP Class/Object function reference manual