search
HomeBackend DevelopmentPHP TutorialDetailed explanation of Traits and their applications in PHP
Detailed explanation of Traits and their applications in PHPMay 25, 2018 pm 02:37 PM
phptraitDetailed explanation

This article mainly introduces Traits and their applications in PHP in detail, which has certain reference value. Interested friends can refer to it

Starting from PHP version 5.4.0, PHP It provides a new concept of code reuse, which is Trait. Trait literally means "characteristics" and "features". We can understand that using the Trait keyword can add new characteristics to classes in PHP.

Everyone who is familiar with object-oriented knows that there are two methods of code reuse commonly used in software development: inheritance and polymorphism. In PHP, only single inheritance can be achieved. Traits avoid this. The following is a comparative explanation through a simple example.

1. Inheritance VS Polymorphism VS Trait

There are now two classes: Publish.php and Answer.php. To add LOG function to it, record the actions inside the class. There are several options:

Inheritance
Polymorphism
Trait

1.1. Inheritance

As shown:

The code structure is as follows:

// Log.php
<?php
Class Log
{
 public function startLog()
 {
  // echo ...
 }

 public function endLog()
 {
  // echo ...
 }
}

// Publish.php
<?php
Class Publish extends Log
{

} // Answer.php
<?php
Class Answer extends Log
{

}

You can see that inheritance does meet the requirements. But this violates the object-oriented principle. The relationship between operations such as Publish and Answer and Log is not the relationship between the subclass and the parent class. So it is not recommended to use it this way.

1.2. Polymorphism

As shown:

##Implementation code:


 // Log.php
<?php
Interface Log
{
 public function startLog();
 public function endLog();
}

// Publish.php
<?php
Class Publish implements Log
{
 public function startLog()
 {
  // TODO: Implement startLog() method.
 }
 public function endLog()
 {
  // TODO: Implement endLog() method.
 }
}

// Answer.php
<?php
Class Answer implements Log
{
 public function startLog()
 {
  // TODO: Implement startLog() method.
 }
 public function endLog()
 {
  // TODO: Implement endLog() method.
 }
}

The logging operations should be the same, so the logging implementation in the Publish and Answer actions is also the same. Obviously, this violates the DRY (Don't Repeat Yourself) principle. Therefore, it is not recommended to implement it this way.


1.3. Trait

As shown:


##The implementation code is as follows:


 // Log.php
<?php
trait Log{
 public function startLog() {
  // echo ..
 }
 public function endLog() {
  // echo ..
 }
}

// Publish.php
<?php
class Publish {
 use Log;
}
$publish = new Publish();
$publish->startLog();
$publish->endLog();

// Answer.php
<?php
class Answer {
 use Log;
}
$answer = new Answer();
$answer->startLog();
$answer->endLog();

As you can see, we have achieved code reuse without increasing the complexity of the code.


1.4. Conclusion
Although the inheritance method can also solve the problem, its idea goes against the object-oriented approach. The principle seems very crude; the polymorphic method is also feasible, but it does not comply with the DRY principle in software development and increases maintenance costs. The Trait method avoids the above shortcomings and achieves code reuse relatively elegantly.


2. Scope of Trait


After understanding the benefits of Trait, we also need to understand the rules in its implementation. Let’s talk about it first. Scope. This is easier to prove. The implementation code is as follows:


 <?php
class Publish {
 use Log;
 public function doPublish() {
  $this->publicF();
  $this->protectF();
  $this->privateF();
 }
}
$publish = new Publish();
$publish->doPublish();

The output result of executing the above code is as follows:


public functionprotected functionprivate function


It can be found that the scope of Trait is visible inside the Trait class that references it. It can be understood that the use keyword copies the implementation code of the Trait into the class that references the Trait.


3. Priority of attributes in Trait


When it comes to priority, there must be a reference for comparison, here is the reference The object refers to the Trait's class and its parent class.


Use the following code to prove the priority of attributes in the Trait application:


 <?php
trait Log
{
 public function publicF()
 {
  echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
 }
 protected function protectF()
 {
  echo __METHOD__ . &#39; protected function&#39; . PHP_EOL;
 }
}

class Question
{
 public function publicF()
 {
  echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
 }
 protected function protectF()
 {
  echo __METHOD__ . &#39; protected function&#39; . PHP_EOL;
 }
}

class Publish extends Question
{
 use Log;

 public function publicF()
 {
  echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
 }
 public function doPublish()
 {
  $this->publicF();
  $this->protectF();
 }
}
$publish = new Publish();
$publish->doPublish();

The output of the above code The results are as follows:


Publish::publicF public functionLog::protectF protected function

Through the above example, it can be concluded that The priorities in Trait applications are as follows:

1. Members from the current class override the trait's methods

2. The trait overrides the inherited methods


The priority of class members is: Current class>Trait>Parent class


4. Insteadof and As keyword


In one class, multiple Traits can be referenced. As follows:


 <?php
trait Log
{
  public function startLog()
  {
    echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
  }
  protected function endLog()
  {
    echo __METHOD__ . &#39; protected function&#39; . PHP_EOL;
  }
}

trait Check
{
  public function parameterCheck($parameters) {
    // do sth
  }
}

class Publish extends Question
{
  use Log,Check;
  public function doPublish($para) {
    $this->startLog();
    $this->parameterCheck($para);
    $this->endLog();
  }
}

Through the above method, we can reference multiple Traits in a class. When referencing multiple Traits, it is easy to cause problems. The most common problem is what to do if there are properties or methods with the same name in two Traits? At this time, you need to use the keywords Insteadof and as. .Please see the following implementation code:

 <?php

trait Log
{
  public function parameterCheck($parameters)
  {
    echo __METHOD__ . &#39; parameter check&#39; . $parameters . PHP_EOL;
  }

  public function startLog()
  {
    echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
  }
}

trait Check
{
  public function parameterCheck($parameters)
  {
    echo __METHOD__ . &#39; parameter check&#39; . $parameters . PHP_EOL;
  }

  public function startLog()
  {
    echo __METHOD__ . &#39; public function&#39; . PHP_EOL;
  }
}

class Publish
{
  use Check, Log {
    Check::parameterCheck insteadof Log;
    Log::startLog insteadof Check;
    Check::startLog as csl;
  }

  public function doPublish()
  {
    $this->startLog();
    $this->parameterCheck(&#39;params&#39;);
    $this->csl();
  }
}

$publish = new Publish();
$publish->doPublish();

执行上述代码,输出结果如下:
 Log::startLog public function
Check::parameterCheck parameter checkparams
Check::startLog public function

就如字面意思一般,insteadof关键字用前者取代了后者,as 关键字给被取代的方法起了一个别名。 

在引用Trait时,使用了use关键字,use关键字也用来引用命名空间。两者的区别在于,引用Trait时是在class内部使用的。

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

关于PHP中的trait简单介绍

PHP中trait使用方法图文详解

php的Traits属性以及基本用法

The above is the detailed content of Detailed explanation of Traits and their applications in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

PHP trait DTO:简化数据传输对象的开发PHP trait DTO:简化数据传输对象的开发Oct 12, 2023 am 09:04 AM

PHPtraitDTO:简化数据传输对象的开发引言:在现代的软件开发中,数据传输对象(DataTransferObject,简称DTO)起到了重要的作用。DTO是一种纯粹的数据容器,用于在层与层之间传递数据。然而,在开发过程中,开发人员需要编写大量的相似的代码来定义和操作DTO。为了简化这一过程,PHP中引入了trait特性,我们可以利用trait特

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

深入了解PHP trait DTO的设计模式与实践深入了解PHP trait DTO的设计模式与实践Oct 12, 2023 am 08:48 AM

深入了解PHPtraitDTO的设计模式与实践Introduction:在PHP开发中,设计模式是必不可少的一部分。其中,DTO(DataTransferObject)是一种常用的设计模式,用于封装数据传输的对象。而在实现DTO的过程中,使用trait(特征)可以有效地提高代码的复用性和灵活性。本文将深入探讨PHP中traitDTO的设计模式与实践

php怎么去除首位数字php怎么去除首位数字Apr 20, 2022 pm 03:23 PM

去除方法:1、使用substr_replace()函数将首位数字替换为空字符串即可,语法“substr_replace($num,"",0,1)”;2、用substr截取从第二位数字开始的全部字符即可,语法“substr($num,1)”。

php有操作时间的方法吗php有操作时间的方法吗Apr 20, 2022 pm 04:24 PM

php有操作时间的方法。php中提供了丰富的日期时间处理方法:1、date(),格式化本地日期和时间;2、mktime(),返回日期的时间戳;3、idate(),格式化本地时间为整数;4、strtotime(),将时间字符串转为时间戳等等。

PHP trait DTO:实现数据传输对象的简洁性与灵活性PHP trait DTO:实现数据传输对象的简洁性与灵活性Oct 12, 2023 am 10:21 AM

PHPtraitDTO:实现数据传输对象的简洁性与灵活性引言:在PHP开发过程中,经常会涉及到数据的传输与处理。而传输对象模式(DataTransferObject,简称DTO)是一种设计模式,它用于将数据在不同层之间传输。在传输过程中,DTO通过封装数据、提供公共访问方法来简化数据的操作。本文将介绍如何使用PHPtrait来实现DT

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft