0CDc0d3r
0CDc0d3r

Reputation: 639

Php Class & Trait methods with same name

I have this specific situation, my trait has a method and my class has a method, both with same name.

I need to use both methods (the one from the trait and the class) Inside that class which contains that same method

namespace Some\Namespace;
use Some\Other\Namespace\TestTrait;

class TestClass {

  use TestTrait;

  public function index()
  {
    // should call the method from the class $this->getId();
    // should also call the method from the trait $this->getId();
  }

  private function getId()
  {
    // some code
  }
}

And in seperate defined Trait:

trait TestTrait
{
    private function getId ()
    {
        // does something
    }
}

Please note this is not pasted code, I might have some typos :P

Upvotes: 11

Views: 6272

Answers (1)

Mateusz Drost
Mateusz Drost

Reputation: 1191

Use trait Conflict Resolution

namespace Some\Namespace;
use Some\Other\Namespace\TestTrait;

class TestClass {

  use TestTrait {
      getId as traitGetId;
  }

  public function index()
  {
    $this->getId();
    $this->traitGetId();
  }

  private function getId()
  {
    // some code
  }
}

Upvotes: 20

Related Questions