2024 年日本 PHP 研討會

trait_exists

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

trait_exists檢查特徵 (trait) 是否存在

說明

trait_exists(字串 $trait, 布林值 $autoload = true): 布林值

參數

trait

要檢查的特性名稱

autoload

如果尚未載入,是否要自動載入

傳回值

如果特性存在,則傳回 true,否則傳回 false

新增註解

使用者貢獻的註解 3 則註解

Lubaev.K
11 年前
<?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!!!
astinus dot eberhard at gmail dot com
7 年前
特性與類別自動載入機制相容 - 事實上,如果您查看 trait_exists 函式的原始碼,您會發現類似的程式碼片段(請參閱 Zend/zend_builtin_functions.c)
valerio dot bozzolan at gmail dot com
8 年前
$autoload 的預設值是什麼?特性是如何自動載入的?是否有類似 spl_autoload() 的機制用於特性?
To Top