class Foo {
public function sampleA(){
echo "something ...";
}
}
class Bar {
public function sampleB(){
echo "something ...";
}
}
$objectA = new Foo();
I want to call $objectA->sampleB() directly, not $objectA->somevariable->sampleB(); How to do this?
One possibility is to simply change the class declaration:
class Foo extends Bar {
The other way around is also possible; it really depends on your use-case. Traits are also a possibility.
trait Bar {
public function sampleB(){
echo "something ...";
}
}
class Foo {
use Bar;
public function sampleA(){
echo "something ...";
}
}
You need to create a facade to the two classes;
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();
}
}
You may try to use traits
(php 5.4+) for multiple inheritance:
<?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();
?>
Shows:
Foo::sampleA
Bar::sampleB