1
class Foo {
    public function sampleA(){
        echo "something ...";
    }
}

class Bar {
    public function sampleB(){
        echo "something ...";
    }
}

$objectA = new Foo();

我想直接调用 $objectA->sampleB(),而不是 $objectA->somevariable->sampleB(); 这个怎么做?

4

3 回答 3

3

您可以尝试使用traits(php 5.4 +) 进行多重继承:

<?php
header('Content-Type: text/plain');

trait Foo {
    public function sampleA(){
        echo __METHOD__, PHP_EOL;
    }
}

trait Bar {
    public function sampleB(){
        echo __METHOD__, PHP_EOL;
    }
}

class Baz {
    use Foo, Bar;
}

$test = new Baz();
$test->sampleA();
$test->sampleB();
?>

显示:

Foo::sampleA
Bar::sampleB
于 2013-06-12T02:45:30.703 回答
3

一种可能性是简单地更改类声明:

class Foo extends Bar {

反过来也是可以的;这真的取决于你的用例。特质也是一种可能。

trait Bar {
    public function sampleB(){
        echo "something ...";
    }
}

class Foo {
    use Bar;

    public function sampleA(){
        echo "something ...";
    }
}
于 2013-06-12T02:40:37.680 回答
2

您需要为这两个类创建一个外观;

class FooBar {
    protected $foo;
    protected $bar;

    public function __construct (Foo $foo, Bar $bar){
        $this->foo = $foo;
        $this->bar = $bar;
    }

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

    public function sampleB() {
          return $this->bar->sampleB();
    }
}
于 2013-06-12T02:41:49.233 回答