4

I have three traits.

Trait Param, GroupId and SessionId. Traits GroupId and SessionId include Param.

Class GroupSession include traits GroupId and 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();

When I try to run this code I get an error:

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

Tell me, please, how to resolve this problem?

Thank you!

2
  • 1
    Would be easier if GroupSession imported Param instead of GroupId/SessionId doing so. The latter two traits just expect the importing class to provide a getParam/setParam method. Since GroupSession in your implementation has to take care of/modify the traits anyway, I don't think that's a disadvantage. Commented Dec 1, 2015 at 8:36
  • @VolkerK, thank you! Now my problem is solved by this way. But I think, that is not native method. Why? Because our traits needs to implemetation some methods in classes, that include its. Commented Dec 2, 2015 at 10:30

1 Answer 1

2

Resolves to method naming conflict

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.