php trait是什么意思

发布时间:2024-08-20 点击:63
php trait是为类似php的单继承语言而准备的一种代码复用机制,trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用method。
trait
自 php 5.4.0 起,php 实现了一种代码复用的方法,称为 trait。
trait 是为类似 php 的单继承语言而准备的一种代码复用机制。trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。trait 和 class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 mixin 类相关典型问题。
trait 和 class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 class 之间不需要继承。
example #1 trait 示例
<?phptrait ezcreflectionreturninfo { function getreturntype() { /*1*/ } function getreturndescription() { /*2*/ }}class ezcreflectionmethod extends reflectionmethod { use ezcreflectionreturninfo; /* ... */}class ezcreflectionfunction extends reflectionfunction { use ezcreflectionreturninfo; /* ... */}?>优先级 ?
从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。
example #2 优先顺序示例
从基类继承的成员被插入的 sayworld trait 中的 myhelloworld 方法所覆盖。其行为 myhelloworld 类中定义的方法一致。优先顺序是当前类中的方法会覆盖 trait 方法,而 trait 方法又覆盖了基类中的方法。
<?phpclass base { public function sayhello() { echo 'hello '; }}trait sayworld { public function sayhello() { parent::sayhello(); echo 'world!'; }}class myhelloworld extends base { use sayworld;}$o = new myhelloworld();$o->sayhello();?>以上例程会输出:
hello world!example #3 另一个优先级顺序的例子
<?phptrait helloworld { public function sayhello() { echo 'hello world!'; }}class theworldisnotenough { use helloworld; public function sayhello() { echo 'hello universe!'; }}$o = new theworldisnotenough();$o->sayhello();?>以上例程会输出:
hello universe!更多相关知识,请访问php中文网!

php中system的意思是什么
备案授权问题??-备案平台
【黄山seo】【搜索引擎优化seo】选择合适的关键词很重要
【宿州网站建设】网站排名不稳定怎么解决?
云主机需要托管吗
ubuntu如何安装php curl方法
南京云主机服务器价格多少钱一台
阿里云服务器多久才能备案