PHP类和Trait方法同名问题

10

我有一个特定的情况:我的特质(trait)有一个方法,而我的类也有一个同名的方法。

我需要在包含这个同名方法的类内部同时使用这两个方法(来自特质和类的方法)。

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
  }
}

并在单独定义的Trait中:

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

请注意,这不是复制的代码,可能存在一些打字错误 :P
1个回答

19

使用 trait 冲突解决

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
  }
}

感谢您的回答(抱歉回复晚了),我想这个方法会有效,但我还是想在我的代码中测试一下,以确保百分之百正确 :) - 0CDc0d3r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接