php - Importing methods from other classes?
311
Can I import methods from other classes without using the inheritance of 'extends' from them?
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();
}
}
Usage,
$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
Ideally,
var_dump($boo->fooMethod()); // string 'foo method' (length=10)
var_dump($boo->tooMethod()); // string 'too method' (length=10)
Is it possible?
EDIT:
I know I can achieve it like this,
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();
}
}
But I am hoping for importing the methods without retyping them. Is it possible?
Answer
Solution:
Yes. traits have been added in PHP 5.4, and they do exactly what you want:
The manual says it beautifully:
Here's a sample:
Answer
Solution:
you can add a __call method in your Boo class:
with as result:
returns: