您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

代码复用Trait使用步奏详解

2025/9/20 8:38:44发布24次查看
这次给大家带来代码复用trait使用步奏详解,代码复用trait使用步的注意事项有哪些,下面就是实战案例,一起来看一下。
从php的5.4.0版本开始,php提供了一种全新的代码复用的概念,那就是trait。trait其字面意思是特性、特点,我们可以理解为,使用trait关键字,可以为php中的类添加新的特性。
熟悉面向对象的都知道,软件开发中常用的代码复用有继承和多态两种方式。在php中,只能实现单继承。而trait则避免了这点。下面通过简单的额例子来进行对比说明。
1. 继承 vs 多态 vs trait
现在有publish.php和answer.php这两个类。要在其中添加log功能,记录类内部的动作。有以下几种方案:
继承
多态
trait
1.1. 继承
代码结构如下:
// log.php<?phpclass log{ publicfunctionstartlog() { // echo ... } publicfunctionendlog() { // echo ... }} // publish.php<?phpclass publishextendslog{} // answer.php<?phpclass answerextendslog{}
1.2. 多态
实现代码:
// log.php<?phpinterface log{ publicfunctionstartlog(); publicfunctionendlog();} // publish.php<?phpclass publishimplementslog{ publicfunctionstartlog() { // todo: implement startlog() method. } publicfunctionendlog() { // todo: implement endlog() method. }} // answer.php<?phpclass answerimplementslog{ publicfunctionstartlog() { // todo: implement startlog() method. } publicfunctionendlog() { // todo: implement endlog() method. }}
1.3. trait
实现代码如下:
// log.php<?phptrait log{ publicfunctionstartlog() { // echo .. } publicfunctionendlog() { // echo .. }} // publish.php<?phpclasspublish { uselog;}$publish=newpublish();$publish->startlog();$publish->endlog(); // answer.php<?phpclassanswer { uselog;}$answer=newanswer();$answer->startlog();$answer->endlog();
1.4. 结论
继承的方式虽然也能解决问题,但其思路违背了面向对象的原则,显得很粗暴;多态方式也可行,但不符合软件开发中的dry原则,增加了维护成本。而trait方式则避免了上述的不足之处,相对优雅的实现了代码的复用。
2. trait的作用域
了解了trait的好处,我们还需要了解其实现中的规则,先来说一下作用域。这个比较好证明,实现代码如下:
<?phpclasspublish { uselog; publicfunctiondopublish() { $this->publicf(); $this->protectf(); $this->privatef(); }} $publish=newpublish();$publish->dopublish(); publicfunctionprotectedfunctionprivatefunction
可以发现,trait的作用域在引用该trait类的内部是都可见的。可以理解为use关键字将trait的实现代码copy了一份到引用该trait的类中。
3. trait中属性的优先级
说到优先级,就必须要有一个对比的参照物,这里的参照对象时引用trait的类及其父类。
通过以下的代码来证明trait应用中的属性的优先级:
<?phptrait log{ publicfunctionpublicf() { echomethod.' public function'. php_eol; } protectedfunctionprotectf() { echomethod.' protected function'. php_eol; }}classquestion{ publicfunctionpublicf() { echomethod.' public function'. php_eol; } protectedfunctionprotectf() { echomethod.' protected function'. php_eol; }}classpublishextendsquestion{ uselog; publicfunctionpublicf() { echomethod.' public function'. php_eol; } publicfunctiondopublish() { $this->publicf(); $this->protectf(); }} $publish=newpublish();$publish->dopublish(); 上述代码的输出结果如下: publish::publicfpublicfunctionlog::protectfprotectedfunction
来自当前类的成员覆盖了 trait 的方法
trait 覆盖了被继承的方法
类成员优先级为:当前类>trait>父类
就如字面意思一般,insteadof关键字用前者取代了后者,as关键字给被取代的方法起了一个别名。
在引用trait时,使用了use关键字,use关键字也用来引用命名空间。两者的区别在于,引用trait时是在class内部使用的。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
php怎么移除数组中的空值或者空元素
php实现一个日志功能
以上就是代码复用trait使用步奏详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product