PHP实现了一种重用代码的方法,即Traits。 PHP中的trait_exists()函数是一个内置函数,用于检查特征是否存在。此函数接受特征名称和自动加载作为参数,如果特征存在,则返回true,否则返回false,如果发生错误则返回null。
用法:
trait_exists ( string $traitname , bool $autoload = ? ):bool
参数:该函数接受上面提到和下面描述的两个参数。
$traitname:此参数包含特征的名称。
$autoload:此参数是一个布尔值,它指示是否自动加载(如果尚未加载)。
返回值:
如果存在特征,则返回true。
如果特征不存在,则返回false。
对于遇到的任何错误,它返回null。
范例1:
PHP
// Created trait Programming
trait Programming
{
// Declared static instance
private static $instance;
protected $temp;
// Defining static function in trait to Reuse
public static function Designing()
{
self::$instance = new static();
// Magic constant __TRAIT__ in PHP
// It gets the class name for the static method called.
self::$instance->temp = get_called_class().' '.__TRAIT__;
return self::$instance;
}
}
// Checking if 'Programming' Trait exists
if ( trait_exists( 'Programming' ) )
{
class Initializing
{
// Reusing trait 'Programming'
use Programming;
public function text( $strParam )
{
return $this->temp.$strParam;
}
}
}
echo Initializing::Designing()->text('!!!');
?>
输出:
Initializing Programming!!!
范例2:
PHP
// Creating Base class
class Base
{
public function callBase()
{
echo 'This is base function!'."
";
}
}
// Creating Trait
trait myTrait {
public function callBase()
{
parent::callBase();
echo 'This is trait function!'."
";
}
}
// Using myTrait
class myClass extends Base
{
use myTrait;
}
$myObject = new myClass();
$myObject->callBase();
// Checking if trait exists
if(trait_exists( "myTrait"))
{
echo "\n myTrait exists! \n";
}
else
{
echo "\n myTrait does not exists! \n";
}
?>
输出:
This is base function!
This is trait function!
myTrait exists!