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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40299080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:40:03  来源:igfitidea点击:

Is there a way to extend a trait in PHP?

phplaraveltraitsphp-7

提问by Yevgeniy Afanasyev

I want to use functionality of an existing traitand create my own traiton top of it only to later apply it on classes.

我想使用现有的功能traittrait在它之上创建我自己的功能,以便以后将其应用于类。

I want to extend Laravel SoftDeletestrait to make SaveWithHistoryfunction, so it will create a copy of a record as a deleted record. I also want to extend it with record_made_by_user_idfield.

我想扩展Laravel SoftDeletes特征以生成SaveWithHistory函数,因此它将创建记录的副本作为已删除的记录。我也想用record_made_by_user_id字段扩展它。

回答by Filip Koblański

Yes, there is. You just have to define new trait like this:

就在这里。你只需要像这样定义新的特征:

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

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

        //your implementation
    }
}