Home > PHP Framework > Laravel > body text

What is trait in laravel

WBOY
Release: 2022-01-13 17:08:16
Original
2183 people have browsed it

In laravel, traits are a code reuse mechanism prepared for single inheritance languages ​​like PHP. Traits are used to reduce the restrictions of single inheritance languages ​​and enable developers to freely work within different hierarchies. Reusing methods in independent classes can be simply understood as an implementation method to facilitate code reuse.

What is trait in laravel

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

What is trait in laravel

Trait is a code reuse mechanism prepared for single inheritance languages ​​like PHP. Traits are designed to reduce the limitations of single-inheritance languages ​​and allow developers to freely reuse methods in independent classes within different hierarchies. The semantics of Trait and Class composition define a way to reduce complexity and avoid the typical problems associated with traditional multiple inheritance and Mixin classes.

First we need to know how to define a Trait. The keyword used is trait

namespace App\Traits;
trait HasCreator
{
}
Copy after login

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();
    }
}
Copy after login

to merge the methods in the Trait into the model. Just use it and then call it as you declared.

There is actually a priority here: calling class>Trait> parent class

trait SoftDeletes
{
    protected $forceDeleting = false;
    public static function bootSoftDeletes()
    {
        ...
    }
    public function forceDelete()
    {
      ...
    }
}
Copy after login

trait can define properties and methods

Method name in trait: hasCreator () is changed to bootHasCreator and will be called by default when using

Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of What is trait in laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!