【问题标题】:PHP: dealing with traits with methods of same namePHP:使用同名方法处理特征
【发布时间】:2014-06-29 00:38:19
【问题描述】:

我在这个网站和谷歌上搜索了所有内容,最终创建了这个帐户...
我需要一些关于 php、traits 和 classes 的帮助。我有这 2 个不同的特征,它们有一些同名的方法。

问题在于我需要他们两个!我不能用...

下面是一个示例代码: http://sandbox.onlinephpfunctions.com/code/b69f8e73cccd2dfd16f9d24c5d8502b21083c1a3

trait traitA {
    protected $myvar;
    public function myfunc($a) { $this->myvar = $a; }
}

trait traitB
{
    public function myfunc($a) { $this->myvar = $a * $a; }
}


class myclass 
{
    protected $othervar;

    use traitA, traitB {
        traitA::myfunc as protected t1_myfunc;
        traitB::myfunc as protected t2_myfunc;
    }

    public function func($a) {
        $this->myvar = $a * 10;
        $this->othervar = t2_myfunc($a);
    }

    public function get() { 
        echo "myvar: " . $this->myvar . " - othervar: " . $this->othervar; 
    }
}

$o = new myclass;
$o->func(2);
$o->get();

所以,这个例子的结尾很明显

致命错误:尚未应用特征方法 myfunc,因为与 myclass 上的其他特征方法发生冲突

如何在不更改这些方法名称的情况下解决这个问题?有可能吗?

顺便说一句,这是我这辈子见过的最糟糕的编辑器!

【问题讨论】:

    标签: php class inheritance scope traits


    【解决方案1】:

    你仍然需要解决冲突以支持一个特征。在这里,您只为名称起别名。不是重命名,而是别名。

    添加到use 块:

    traitA::myfunc insteadof traitB;
    

    (或traitB::myfunc insteadof traitA;

    它应该可以工作。

    您现在有两个想要的别名,并且冲突也已解决。

    【讨论】:

    • 太棒了!我在$this->othervar = $this-> t2_myfunc($a) xD 你的解决方案有效,不敢相信它这么简单:S
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2013-12-21
    • 2014-02-17
    • 2018-04-11
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多