laravel trait 定义 和 使用
Trait是一种在单继承语言(如PHP)中重用代码的机制。Trait旨在通过使开发人员能够在生活在不同类层次结构中的多个独立类中自由地重用方法集来减少单继承的某些限制。Traits和类组合的语义以降低复杂性的方式定义,并避免了与多重继承和Mixins相关的典型问题。
Trait类似于类,但仅用于以细粒度和一致的方式对功能进行分组。无法自行实例化Trait。它是对传统继承的补充,可以实现行为的横向组合; 也就是说,类成员的应用程序不需要继承。
Trait仅仅是您希望包含在另一个类中的一组方法。与抽象类一样,Trait不能自己实例化。
案例使用
一、在App/Http 下新建文件夹 Traits
二、在文件夹Traits下 新建 TestTrait文件
<?php
/**
* Created by PhpStorm.
* User: Lenovo
* Date: 29/4/2021
* Time: 下午5:07
*/
namespace App\Http\Traits;
trait TestTrait
{
//生成唯一Id
public function getUniqueId(){
return uniqid(mt_rand(10,99));
}
}
三、在其他类中继承使用 TestTrait
<?php
namespace App\Console\Commands\Test;
use App\Http\Traits\TestTrait;
use Illuminate\Console\Command;
class Test extends Command
{
//引用trait
use TestTrait;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'test';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->createUniqid();
}
//只要通过use trait 就可以像使用自己的方法一样使用 trait方法
private function createUniqid(){
$unique_id = $this->getUniqueId();
}
}