PHP特征冲突(特质参数)

时间:2015-12-01 07:19:39

标签: php

我有三个特点。

特质ParamGroupIdSessionId。特征GroupIdSessionId包含Param

班级GroupSession包括特征GroupIdSessionId

<?php

trait Param
{
    private $params = [];

    public function setParams($params)
    {
        $this->params = $params;
    }

    public function getParam($param)
    {
        return isset($this->params[$param])
            ? $this->params[$param]
            : null;
    }
}

trait GroupId
{
    use Param;

    public function getGroupId()
    {
        return $this->getParam('group.id');
    }
}

trait SessionId
{
    use Param;

    public function getSessionId()
    {
        return $this->getParam('session.id');
    }
}

class GroupSession
{
    use GroupId {
        GroupId::setParams insteadOf SessionId;
        GroupId::getParam insteadOf SessionId;
    }
    use SessionId;
}

$t = new GroupSession();

当我尝试运行此代码时出现错误:

GroupId and SessionId define the same property ($params) in the composition of GroupSession. However, the definition differs and is considered incompatible.

请告诉我,如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方法命名冲突

trait A
{
    public function smallTalk()
    {
        echo "I am form trait A and method smallTalk";
        echo "<br>";
    }

    public function bigTalk()
    {
        echo "I am form trait A and method bigTalk";
        echo "<br>";
    }
}


trait B
{
    public function smallTalk()
    {
        echo "I am form trait B and method smallTalk";
        echo "<br>";
    }

    public function bigTalk()
    {
        echo "I am form trait B and method bigTalk";
        echo "<br>";
    }
}

class AB
{
    use A, B {
    A::bigTalk insteadof B;
    B::bigTalk as gazi;
    B::smallTalk insteadof A;
    A::smallTalk as anis;
    }
}

$obj1 = new AB;
$obj1->bigTalk();
$obj1->gazi();
$obj1->smallTalk();
$obj1->anis();