有没有办法扩展 PHP 中的特征?

Is there a way to extend a trait in PHP?

我想使用现有 trait 的功能并在其之上创建我自己的 trait 只是为了稍后将其应用于 类。

我想扩展 Laravel SoftDeletes 特征来实现 SaveWithHistory 功能,因此它将创建记录的副本作为已删除的记录。我还想用 record_made_by_user_id 字段扩展它。

是的,有。您只需要像这样定义新特征:

trait MySoftDeletes 
{
    use SoftDeletes {
        SoftDeletes::saveWithHistory as parentSaveWithHistory;
    }

    public function saveWithHistory() {
        $this->parentSaveWithHistory();

        //your implementation
    }
}

我有不同的方法。 ParentSaveWithHistory 仍然适用于此特征的方法,因此至少应定义为私有。

trait MySoftDeletes
{
    use SoftDeletes {
        saveWithHistory as private parentSaveWithHistory; 
    }

    public function saveWithHistory()
    {
        $this->parentSaveWithHistory();
    }
}

还要考虑 'overriding' 特征中的方法:

use SoftDeletes, MySoftDeletes {
    MySoftDeletes::saveWithHistory insteadof SoftDeletes;
}

此代码使用 MySoftDeletes 中的方法 saveWithHistory,即使它存在于 SoftDeletes.