0
votes

I have a class which extends an other class and uses a trait.

class A extends ABase
{
    use MyTrait;
    //...
}

The extended class (ABase) extends an other class (ABase2), which extends an abstract class (ABase3).

When an A class is created, the trait constructor is executed because there is no constructor defined in A. At the same time, the trait constructor calls a method (configureOptions) which is defined in the trait, but also in the abstract class ABase3 with the same visibility (protected).

trait MyTrait
{
    public function __construct($options)
    {
        //...
        $this->configureOptions($resolver);
       //... 
    }

    protected function configureOptions($resolver)
    {
        // Define options
    }
}

What I don't understand is that when configureOptions is called from the trait, the method executed is not the method defined in the trait, but the one defined in the abstract class (ABase3).

As PHP docs says: An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.

Doesn't say nothing about calling methods from the same trait, but shouldn't check first for the methods inside its own class?

Edit:

Not only the abstract class (ABase3) has the configureOptions method, but also the A class, but again, the method called from the trait should call the own class method. Isn't it?

1

1 Answers

3
votes

I've got the solution from this answer.

class A extends ABase
{
    use MyTrait {
        configureOptions as traitConfigureOptions;
    }
    //...
}

and then, instead of parent::configureOptions($resolver):

$this->traitConfigureOptions($resolver);