我具有以下特征:
<?php
namespace App\Traits;
trait SlugGenerator
{
public static $slugAttributes;
public static function bootSlugGenerator()
{
static::creating(function ($model) {
if(isset(self::$slugAttributes)){
$model->slug = 'a';
} else {
$model->slug = 'b';
}
});
}
}
在这里,我称自己为特质:
<?php
namespace App\Models;
use App\Traits\SlugGenerator;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use SlugGenerator;
protected static $slugAttributes = [
'first_name',
'last_name'
];
}
但是出现以下错误:
App \ Models \ User和App \ Traits \ SlugGenerator定义相同的属性 ($ slugAttributes)组成App \ Models \ User。然而 定义不同,被认为是不兼容的。班级组成
如何覆盖$slugAttributes
变量?
答案 0 :(得分:1)
PHP - Override static variable inside trait
一种可能的解决方案是不像下面的示例那样在您的特征中声明$slugAttributes
:
<?php
trait Foo
{
public function greet()
{
return 'hello ' . $this->target;
}
}
class Bar
{
use Foo;
private $target = 'world';
}
$bar = new Bar();
var_dump($bar->greet());
// > string(11) "hello world"