PHP特征冲突(特质参数)

我有三个特点.

Trait Param,GroupId和SessionId. Traits GroupId和SessionId包括Param.

类GroupSession包括特征GroupId和SessionId

<?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和SessionId在GroupSession的组合中定义相同的属性($params).但是,定义不同并且被认为是不兼容的.

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

谢谢!

最佳答案 解决方法命名冲突

      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();
点赞