Php 我可以只从特征导入一些选定的方法吗?

Php 我可以只从特征导入一些选定的方法吗?,php,traits,Php,Traits,如果一个特征包含多个属性和方法,我可以只导入其中的几个吗 trait MyTrait { public function ok() { echo 'ok'; } public function nope() { echo 'not ok'; } } class MyClass { use MyTrait { MyTrait::ok as ok; } } $mc = new MyC

如果一个特征包含多个属性和方法,我可以只导入其中的几个吗

trait MyTrait
{
    public function ok()
    {
        echo 'ok';
    }

    public function nope()
    {
        echo 'not ok';
    }
}

class MyClass
{
    use MyTrait {
        MyTrait::ok as ok;
    }
}

$mc = new MyClass;

$mc->ok(); // This should work
$mc->nope(); // This shouldn't work
问题是我正在开发一个包,希望从另一个包中导入两个方法(以确保某些操作以相同的方式工作)。但这些方法的特点是包含11个属性和76个方法。我不希望所有这些都污染我的命名空间


有没有办法有选择地进口?还是我必须退回到某种反思的诡计上来?

据我所知,你不能这么做。使用特征基本上是将其内容包含到类中。它定义的属性和方法可能相互依赖

另一种选择是在不包含trait的类中手动定义所需的方法,而是将调用委托给包含trait的类的实例

大概是这样的:

trait MyTrait
{
  public function ok(): void
  {
    echo 'ok';
  }

  public function nope(): void
  {
    echo 'not ok';
  }
}

class MyTraitDelegate
{
  use MyTrait;
}

class MyClass
{
  private MyTraitDelegate $traitDelegate;

  public function __construct()
  {
    $this->traitDelegate = new MyTraitDelegate();
    // Note: you could also inject it, but in this case, not sure it's worth.
  }

  public function ok(): void
  {
    $this->traitDelegate->ok();
  }
}

$mc = new MyClass;

$mc->ok();   // works
$mc->nope(); // method not found