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

时间:2016-10-28 06:14:11

标签: php laravel traits php-7

我想使用现有trait的功能并在其上创建我自己的trait,但稍后才将其应用于类。

确切地说,我想扩展Laravel SoftDeletes特征以使SaveWithHistory函数,因此它将创建记录的当前状态的副本作为已删除的记录。我还想用record_made_by_user_id字段扩展它。

2 个答案:

答案 0 :(得分:87)

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

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

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

        //your implementation
    }
}

答案 1 :(得分:2)

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

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

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

还要考虑特征中的“覆盖”方法:

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

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

相关问题