Laravel 控制器使用使用另一个已使用特征的特征

Laravel controller use trait that uses another used trait

我有一个使用两个特征的控制器,CavityToolsOperationTools

class OperationController extends Controller
{

    use \App\Traits\CavityTools;
    use \App\Traits\OperationTools;

但是,第二个特征 OperationTools usingCavityTools`:

trait OperationTools {
    use \App\Traits\CavityTools;

因此,当我尝试从任何控制器的方法(例如 $this->getProduction() 中使用 OperationTools 的方法时,我得到一个错误,告诉我 CavityTools 中的一个方法是由于冲突未应用:

Trait method cavityPerformanceBetweenTimes has not been applied, because there are collisions with other trait methods on App\Http\Controllers\OperationController

我曾尝试为第二个特征设置别名,use \App\Traits\OperationTools as OpTs; 但它会生成解析错误:

Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ';' or '{'

我该如何解决这个问题?

这是因为两个性状的功能相同。为避免这种情况,您必须在当前 class.

中使用 "InsteadOf"

参考 - Collisions with other trait methods

只需使用 OperationTools 特性,因为 CavityTools 已被使用。

示例代码:

<?php


trait A {
    function a() {
        echo "a trait\n";
    }
}

trait B {
    use A;
    function b() {
        echo "b trait\n";
    }

    function a() {
        echo "a fcn from trait B\n";
    }
}

trait C {
    use B;
    function a() {
        echo "a fcn from C trait\n";
    }

    function b() {
        echo "b fcn from C trait\n";
    }
}


class AClass {
    use A;
}

$classA = new AClass;
$classA->a();
// $classB->b(); // will throw up


class BClass {
    use B;
}

$classB = new BClass;
$classB->a();
$classB->b();

class CClass {
    use C;
}

$classC = new CClass;
$classC->a();
$classC->b();

//输出

a trait
a fcn from trait B
b trait
a fcn from C trait
b fcn from C trait