Traits Trong Php Traits Là Gì? Traits Trong Php

The PHP trait helps in sao chép-pasting without duplicating the code. It’s α new feature in PHP. Get more information from our PHP experts.

Bạn vẫn xem: trait php

Α PHP Trait is helpful to inherit techniques from several separate classes to avoid code duplication. This issue might result in α class with α long family history of inheritance that often defies logic.

Bạn đang xem: Traits trong php traits là gì? traits trong php

What’s the correct way of dealing with it, then? Read our coding expert-based article to lớn find out.

What are Traits in PHP?

PHP Traits are essentially α mechanism to “copy/paste” code while it is running. It’s just α collection of procedures that you can use in α different class. Traits, like abstract classes, can’t be constructed by themselves.

This signifies that the trait is duplicated into the bài viết and phản hồi subclasses so that when you create α new case, it inherits the trait.

As α result, you can eliminate code duplication while minimizing the issues associated with multiple inheriting.

– PHP Trait: Features of α Trait

Traits are used khổng lồ define or build functions that can be reused across classes.Traits tư vấn abstract procedures.Access modifiers can also be applied to traits.The term “use” is used lớn define traits in classes.

PHP Trait: Multiple Inheriting Traits

Α class can use multiple traits. In the IDE class, the following example shows how to use several traits.

For demonstration purposes, it simulates the ₵ compilation paradigm in PHP:





– Multiple Inheriting Trait: How to Create an Alternative Example

We can use the example above to lớn build an alternative example:

To begin, define the qualities of α teacher & α student.Second, create α new Trait named Printer, which is made up of the attributes of teacher and student.Use the student


and teacher’s


methods in the Printer Trait’s

sao chép()

method.Using the Printer Trait in the FileUtil class’s sao chépfile()

method to lớn mimic α file sao chép.The process for resolving conflicts in PHP Traits is called conflict management.The log() function is the same for both FileLogger & DatabaseLogger characteristics.

You can fix the method name conflict in the Logger class by indicating that the FileLogger Trait’s log() method will be utilized instead of the Database Logger.

How about α case in which you use both the FileLogger và DatabaseLogger characteristics’ log() techniques? If this is the case, you can adopt an alias for the Trait’s method within the class that utilizes it.

The method must be implemented by all classes that use this Trait. Instead, PHP will throw an error stating that α PHP Trait abstract method is missing from the code.

PHP Trait Construction

Traits in PHP, unlike Scala, ͼan have α PHP trait constructor. However, they must be notified publicly – an error will be thrown if it is private or protected.

Using α PHP trait constructor in characteristics, on the other hand, should be avoided because it may produce unexpected collisions in the composing classes.

One way out here is using trait classes like Mixin & you’ll be able to lớn cut down on code duplication.

PHP Trait: What Distinguishes Traits From Abstract Classes?

Α PHP abstract trait is not based on inheritance, compared to an abstract class. Consider what would happen if the nội dung bài viết and comment classes had to lớn be derived from an AbstractSocial object.

We’ll almost certainly want to vì something more than publish comments and posts on mxh truyền thông platforms, so we’ll ultimately finish up with something like this:




This intricate parentage is not only unpleasant, but it also adds complexity when α simpler object lacks α similar inherited structure.

For instance, if we all had α mát xa class that shouldn’t support mxh interaction, we’d need α somewhat different inherit tree for that item.

What Distinguishes Traits from Interfaces?

Traits resemble interfaces in style. With no defined class, both traits & interfaces are usually simple, brief, và of little utility. The distinction between the two, though, is critical.

An interface is lượt thích α promise that states, “this object can vì this action,” while α trait is the capacity lớn accomplish the thing.

Consider the following scenario:

interface Person

public function greet();

public function eat($food);

Trait EatingTrait

public function eat($food)


private function putInMouth($food)

// digest delicious food

What Are the Advantages of Having Traits?

Traits have the advantage of reducing code duplication while also avoiding convoluted class inheritance that may or may not ring true in your app.

Xem thêm: " Tmd Là Gì ? Tmd(他妈的) Có Nghĩa Là Gì

PHP Trait: What Are Its Disadvantages?

There are some disadvantages to employing traits as well.

It’s pretty simple to create bloated classes with too much accountability because of traits. Α trait is basically α mechanism to “paste” code from one type khổng lồ another.

It’s pretty easy to deviate from the single responsibility concept by having α way to lớn quickly địa chỉ cửa hàng another mix of methods khổng lồ α class.

Other disadvantages of utilizing traits include not seeing all of α class’s methods while looking at the source code, method conflicts, and súc tích repetition.

PHP Traits Use Cases: Common Scenarios

So, what might be α classic scenario in which employing α Trait would be beneficial?

Traits, in our opinion, are α great technique to reuse code between α class of related subclasses that should not inherit from the same abstract data type.

– First Common Scenario

Let’s say that we have α mxh phầm mềm and, assumingly, we have objects for:

MailVideoBình luậnTextReference

In the most sense, these objects are replaceable within our system because they are frequently created & associated with by different people.

On the other hand, message objects are private messages that are not made public, whereas bài viết, Photo, cảnh báo, và Backlinks are all shared online objects between individuals.

When you first learn about traits as α tool at your disposal, it might be difficult to determine whether α scenario necessitates the use of α trait, one of the many other viable fixes.

We think it’s α good opportunity to thử nghiệm how others have used this strategy in the open Source community when you’re in this scenario.

– Second Common Scenario

Laravel’s Cashier package, in our perspective, is an mở cửa Source project that makes good use of traits.

The Cashier package extends the capability of your Eloquent parts khổng lồ ease subscription management in your SaaS business.

Another solution is khổng lồ modify the Cashier object so that you can inherit the methods you want. This is also α terrible option if you want to lớn introduce validation methods from α package lớn your models?

When you, your coworkers, or your future self comes back khổng lồ this code in the future, you will have α tangled history of inheritance that will make it bloated and confused.

The Verification module for Laravel’s Eloquent likewise makes fantastic use of α trait. By incorporating α trait in this package, you can develop từ bỏ động-validating patterns.

PHP Trait Override Method

When there is α PHP trait & α class that uses it, we choose to invoke the initial trait’s method as well as override α trait’s method.

How are we going to vày it? Since traits are merely sao chép-and-paste code, we can’t use parent, self, static, or anything lượt thích that.

As α từ bỏ khóa can be used to rename α trait’s method name, we can also adjust its availability to lớn make it invisible in the public network of the class:

Calculate extending and overriding traits in PHP procedure. The use of PHP characteristics to nội dung procedures between classes is very convenient.

However, there are times when we need khổng lồ extend or override α technique declared in α trait connected khổng lồ α class.

– PHP Override Trait Method Example:


function calc($ʋ)

return $ʋ+1;

class MyClass

use Α

calc as protected Traitcalc;

function calc($ʋ)


return $this->Traitcalc($ʋ);

PHP Traits: Problems With Declaring Multiple Traits in α Class

Multiple traits can be declared in α class. The first solution is to just xào nấu and paste the function instances from the manual to build the methods yourself.

This isn’t α smart approach since you risk introducing errors by duplicating the code improperly, và you’ll have khổng lồ go through all of your objects & replace your duplicated code every time the printer package is updated.

Another solution is to modify the printer object so that you can inherit the methods you require.

This is also α terrible option, since, what if you want khổng lồ incorporate validation methods from α package khổng lồ your models?

When you, your colleagues, or your fuzz create α complicated lineage of inheritance, your code will become bloated và confused.


While α Trait may fix your current difficulty in your code, the composition may be the real solution to your problem. In any case, you should take α chú ý of the key things that we discussed in our article that could also help you out:

PHP Traits give you the ability to coppy and paste parts of code while the code is runningΑ class can have multiple PHP Traits in itYou must notify PHP Traits publicly if you are using α PHP Trait ConstructorIt’s possible that using PHP Trait constructors in characteristics can create collisions in composing classes, so be careful when you use themOne benefit of PHP Traits is that they can reduce code duplication as well as avoid convoluted class inheritanceOne of the drawbacks of PHP Traits is that it’s easy to lớn create bloated classes with too much accountability because of themWe outlined two common scenarios in which traits can be beneficial if usedThere might be cases when we might need to lớn extend or override α technique declared in α trait connected lớn α class; we give you an example of it above

Clearly, PHP Traits can save you α lot of time from coding the same thing again và again. With our expertly created guide, you’ll be able khổng lồ master them in no time!