从其他类导入方法?

lau*_*kok 1 php oop inheritance multiple-inheritance php-5.5

我可以从其他类导入方法而不使用它们的'extends'继承吗?

class Foo
{
    public function fooMethod() {
        return 'foo method';
    } 
}

class Too
{
    public function tooMethod() {
        return 'too method';
    } 
}

class Boo
{
    public $foo;
    public $too;

    public function __construct()
    {
        $this->foo = new Foo();
        $this->too = new Too();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法,

$boo = new Boo();

var_dump($boo->foo->fooMethod()); // string 'foo method' (length=10)
var_dump($boo->too->tooMethod()); // string 'too method' (length=10)
var_dump($boo->fooMethod()); // Fatal error: Call to undefined method Boo::fooMethod() in 
var_dump($boo->tooMethod()); //Fatal error: Call to undefined method Boo::tooMethod() in 
Run Code Online (Sandbox Code Playgroud)

理想的情况下,

var_dump($boo->fooMethod()); // string 'foo method' (length=10)
var_dump($boo->tooMethod()); // string 'too method' (length=10)
Run Code Online (Sandbox Code Playgroud)

可能吗?

编辑:

我知道我可以这样做,

class Boo
{
    public $foo;
    public $too;

    public function __construct()
    {
        $this->foo = new Foo();
        $this->too = new Too();
    }

    public function fooMethod() {
        return $this->foo->fooMethod();
    }

    public function tooMethod() {
        return $this->too->tooMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我希望在不重新输入方法的情况下导入方法.可能吗?

Vla*_*eda 5

是.在PHP 5.4中添加了特性,它们完全符合您的要求:

手册说得很漂亮:

Trait旨在通过使开发人员能够在生活在不同类层次结构中的多个独立类中自由地重用方法集来减少单个继承的某些限制

这是一个示例:

trait FooTrait {
  public function fooMethod() {
        return 'foo method';
  } 
}

trait TooTrait {
    public function tooMethod() {
        return 'too method';
    } 
}

class Foo
{
    use FooTrait;
}

class Too
{
    use TooTrait;
}

class Boo
{
    use FooTrait;
    use TooTrait;
}

$a = new Boo;
echo $a->fooMethod();
echo $a->tooMethod();
Run Code Online (Sandbox Code Playgroud)