php+exist(),PHP trait_exists()用法及代码示例

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值