Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Class & Trait methods with same name

Tags:

php

traits

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

like image 234
0CDc0d3r Avatar asked Dec 16 '16 14:12

0CDc0d3r


1 Answers

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
  }
}
like image 180
Mateusz Drost Avatar answered Nov 06 '22 04:11

Mateusz Drost