📅  最后修改于: 2023-12-03 15:18:21.320000             🧑  作者: Mango
在 PHP 5.4.0 及以上版本中,引入了 Trait 特性。Trait 是一种代码重用的机制,可在现有的类中复用公共的代码。PHP trait_exists()函数用于检查指定的 Trait 是否被定义,若被定义则返回 true,否则返回 false。
trait_exists( string $traitname [, bool $autoload ] ) : bool
traitname
:必需,要检查的 Trait 名称。
autoload
:可选,如果设置为 true,则在检查 Trait 时会自动调用 __autoload() 函数。
如果 traitname
参数指定的 Trait 已被定义,则返回 true,否则返回 false。
下面是检查一个 Trait 是否存在的示例:
<?php
trait FooTrait {
public function foo() {
echo 'Foo';
}
}
if (trait_exists('FooTrait')) {
// 如果存在 FooTrait,则实例化一个对象并调用 foo() 方法
$obj = new class {
use FooTrait;
};
$obj->foo();
} else {
echo 'Trait FooTrait 未定义';
}
?>
输出:
Foo