这期内容当中小编将会给大家带来有关PHP中特征的特性有哪些,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
自PHP 5.4.0起,PHP实现了代码复用的一个方法,称为特征。
特征是一种为类似PHP的单继承语言而准备的代码复用机制.Trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集.Traits和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(混合)相关的典型问题。
特征和一个类相似,但仅仅旨在用细粒度和一致的方式来组合功能.Trait不能通过它自身来实例化。它为传统继承增加了水平特性的组合,也就是说,应用类的成员不需要继承。
特征是在PHP5.4中加入的,它既不是接口也不是类。主要是为了解决单继承语言的限制。是PHP多重继承的一种解决方案,例如,需要同时继承两个抽象类,这将会是件很麻烦的事情,特质就是为了解决这个问题。它能被加入到一个或多个已经存在的类中,它声明了类能做什么(表明了其接口特性),同时也包含了具体实现(表明了其类特性)
<强>简单使用强>
首先,当然是声明个特征,PHP5.4增加了特质关键字
trait first_trait { function first_method (), {,/* Code Here */,} function second_method (), {,/* Code Here */,} }
同时,如果要在类中使用该特征,那么使用使用关键字
class first_class {//,注意这行,声明使用,first_trait use first_trait; } $ obj =, new first_class ();//,Executing 从而,method 得到特征 美元obj→first_method();//,有效 obj→美元second_method();,//,有效的
<强>使用多个特质
强>
在同个班级中可以使用多个特质
trait first_trait { function first_method (), {, echo “method",,} } trait second_trait  { function second_method (), {, echo “method",,} } class first_class  {//,你using more  than one 特征 use first_trait, second_trait; } $ obj=, new first_class ();//有效 美元obj→first_method ();,//, Print :方法//有效 obj→美元second_method ();,//, Print :,方法
<强>特质之间的嵌套
强>
同时,特征之间也可以相互的嵌套,例如
trait first_trait { function first_method (), {, echo “method",,} } trait second_trait  { use first_trait; function second_method (), {, echo “method",,} } class first_class  {//,你using use second_trait; } $ obj=, new first_class ();//有效 美元obj→first_method ();,//, Print :方法//有效 obj→美元second_method ();,//, Print :,方法
<强>特质的抽象方法(抽象方法)
强>
我们可以在特质中声明需要实现的抽象方法,这样能使使用它的类必须实现它
trait first_trait { function first_method (), {, echo “method",,}//,这里可以加入修饰符,说明调用类必须实现它 abstract public  function second_method (); } class first_method  { use first_trait; function second_method (), {/*,Code Here */} }
<>强特征冲突强>
多个特质之间同时使用难免会冲突,这需要我们去解决.PHP5.4从语法方面带入了相关的关键字语法:不要以及,用法参见
trait first_trait { function first_function (), {, echo “得到First Trait"; } } trait second_trait  {//,这里的名称和,first_trait 一样,会有冲突 function first_function (), {, echo “得到Second Trait"; } } class first_class  { use first_trait, second_trait {//,在这里声明使用,first_trait 的,first_function 替换//,second_trait 中声明的 first_trait: first_function insteadof  second_trait; } }, $ obj =, new first_class ();//,输出:得到First 特征 obj→美元first_function ();
上面就是些特征比较基本的使用了,更详细的可以参考官方手册。这里总结下注意的几点: