trait_exists
(PHP 5 >= 5.4.0)
trait_exists — Checks if the trait exists
Description
bool trait_exists
( string
$traitname
[, bool $autoload
] )
Parameters
-
traitname
-
Name of the trait to check
-
autoload
-
Whether to autoload if not already loaded.
Return Values
Returns TRUE
if trait exists, FALSE
if not, NULL
in case of an error.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения, относящиеся к переменным и типам
- Функции работы с классами и объектами
- __autoload
- call_user_method_array
- call_user_method
- class_alias
- class_exists
- get_called_class
- get_class_methods
- get_class_vars
- get_class
- get_declared_classes
- get_declared_interfaces
- get_declared_traits
- get_object_vars
- get_parent_class
- interface_exists
- is_a
- is_subclass_of
- method_exists
- property_exists
- trait_exists
Коментарии
<?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!!!
What is the default value of $autoload? And in which way traits are autoloaded? Is there something as spl_autoload() for traits?
Traits are compatible with class autoload mechanism - in fact, if you look at source code of trait_exists function, you will find similar peace of code (see Zend/zend_builtin_functions.c)