在 Laravel 中,我有一个 User 类,它扩展了 Authenticatable 并使用名为 Activable 的特征:
class User extends Authenticable {
use Activable;
protected $is_active_column = 'is_active';
}
trait Activable {
/**
* The name of the column with the activable status
*
* @var string
*/
protected $is_active_column = 'is_active';
}
当我尝试在修补程序中查找用户时,出现此错误:
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
PHP Fatal error: App\Models\User and App\Traits\Activable define the same property ($is_active_column) in the composition of App\Models\User. However, the definition differs and is considered incompatible.
最佳答案
这是预期的行为。 The PHP documentation on Traits is explicit about this
Properties
Traits can also define properties.
Example #12 Defining Properties
<?php trait PropertiesTrait { public $x = 1; } class PropertiesExample { use PropertiesTrait; } $example = new PropertiesExample; $example->x; ?>
If a trait defines a property then a class can not define a property with the same name unless it is compatible (same visibility and initial value), otherwise a fatal error is issued.
Example #13 Conflict Resolution
<?php trait PropertiesTrait { public $same = true; public $different = false; } class PropertiesExample { use PropertiesTrait; public $same = true; public $different = true; // Fatal error } ?>
关于php - 如果它们相同,为什么我会得到 "definition differs"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71341392/