1

我可以从其他类导入方法而不使用它们的“扩展”继承吗?

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

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

4

2 回答 2

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();
于 2014-07-31T15:16:37.017 回答
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
于 2014-07-31T15:14:28.787 回答