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)
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
trait_exists — 检查指定的 trait 是否存在
$traitname
, bool $autoload
= ?
) : bool
traitname
待检查的 trait 的名称
autoload
如果尚未加载,是否使用自动加载(autoload)。
如果 trait 存在返回 true
,不存在则返回 false
。发生错误的时候返回 null
。
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)
What is the default value of $autoload? And in which way traits are autoloaded? Is there something as spl_autoload() for traits?
<?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!!!