从其他类导入方法?

时间:2014-07-31 15:07:28

标签: 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();
    }
}

用法,

$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 

理想地,

var_dump($boo->fooMethod()); // string 'foo method' (length=10)
var_dump($boo->tooMethod()); // string 'too method' (length=10)

有可能吗?

编辑:

我知道我可以像这样实现它,

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();
    }
}

但我希望导入方法而无需重新输入。有可能吗?

2 个答案:

答案 0 :(得分:5)

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

手册说得很漂亮:

  

Trait旨在通过启用a来减少单个继承的一些限制   开发人员可以在几个独立的类中自由地重用方法集   不同的类层次结构

以下是一个示例:

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();

答案 1 :(得分:2)

您可以在Boo类中添加__call方法:

public function __call($method, $args)
{
    if (method_exists($this->foo, $method)) {
        return call_user_func_array(array($this->foo, $method), $args);
    }
    else if (method_exists($this->too, $method)) {
        return call_user_func_array(array($this->too, $method), $args);
    }
    else {
        throw new Exception("Unknown method " . $method);
    }
}

结果:

$boo = new Boo();

var_dump($boo->foo->fooMethod());
var_dump($boo->too->tooMethod());
var_dump($boo->fooMethod());
var_dump($boo->tooMethod());
var_dump($boo->newMethod());

返回:

string(10) "foo method"
string(10) "too method"
string(10) "foo method"
string(10) "too method"
PHP Fatal error:  Uncaught exception 'Exception' with message 'Unknown method newMethod' in /tmp/call.php:38
Stack trace:
#0 /tmp/call.php(49): Boo->__call('newMethod', Array)
#1 /tmp/call.php(49): Boo->newMethod()
#2 {main}
  thrown in /tmp/call.php on line 38