Get the App
SLTechnology News&Howtos  ›  Development  › 

What does trait mean in laravel

Shulou Source: shulou.com Published: 2022-06-02 02:37:15 09月29日 Update

This article mainly introduces the meaning of trait in laravel. It has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.

In laravel, trait is a kind of code reuse mechanism for single inheritance language similar to PHP. Trait is used to reduce the limitation of single inheritance language, so that developers can freely reuse method in independent classes in different hierarchies, which can be simply understood as an implementation way to facilitate code reuse.

This article operating environment: Windows10 system, Laravel6 version, Dell G3 computer.

What is trait in laravel

Trait is a code reuse mechanism for single inheritance languages like PHP. In order to reduce the limitation of single inheritance language, Trait gives developers the freedom to reuse method in separate classes within different hierarchies. The semantics of the combination of Trait and Class define a way to reduce complexity and avoid typical problems related to traditional multi-inheritance and Mixin classes.

First we need to know how to define a Trait, using the keyword trait

Namespace App\ Traits;trait HasCreator {}

Call

Namespace App;use App\ Traits\ HasCreator;use Illuminate\ Database\ Eloquent\ Model;use Illuminate\ Database\ Eloquent\ SoftDeletes;class Post extends Model {use HasCreator, SoftDeletes; protected $fillable = ['title',' user_id']; protected static function boot () {parent::boot (); self::hasCreator ();}}

Merge the methods in Trait into the model, use them if you want to use them, and then call them as you declare them.

There is actually a priority in this: calling class > Trait > parent class

Trait SoftDeletes {protected $forceDeleting = false; public static function bootSoftDeletes () {...} public function forceDelete () {...}}

Trait can define properties and methods

The name of the method in trait: hasCreator () is changed to bootHasCreator, which is called by default when use

Thank you for reading this article carefully. I hope the article "what does trait mean in laravel" shared by the editor will be helpful to everyone? at the same time, I also hope that you will support and pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

Tags: Reuse articles language code method meaning difference freedom people hierarchy way mechanism structure preparation development independence limitation complexity value priority Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia vpn Linux MariaDB Docker