php - 如果它们相同,为什么我会得到 "definition differs"?

标签 php laravel properties traits

在 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/

相关文章:

c++ - 成员函数指针作为构造函数参数

php - Phalcon session 适配器?安全吗?

php - 我应该将其更改为 CONCAT 吗?

php - Laravel:数据库 - 更多 "log column"

asp.net - asp.net 中的用户控件 (ascx) 及其可绑定(bind)属性未显示在数据容器中

ios - @property copy 与 readonly 结合使用是否有意义?

php - 使用 PHP 创建规范 URL

PHP POST 打印复选框条目 : nothing I have found on forums works

php - 升级 laravel 5.1 - 5.4 时如何修复 'You must set the encryption key going forward to improve the security of this library' 错误

mysql - 如何使用 Scope 在 Eloquent ORM 中选择除(A 和 B)以外的所有行?