可能重复:
我可以在PHP中使用多于1个类扩展一个类吗?
我有一个有几个子类的类,但是我现在正在添加另一个类,我也想成为父类的子类,但是我也想使用其他子类中的许多函数.
我想过只是将相应的函数从另一个子类移动到父类,但不认为这是真的需要,因为只有这两个子类才能使用它们所以希望我可以从主要的父类和一个现有的子类.
alx*_*xbl 14
你可以扩展子类来继承它的父类和子函数,我认为这是你想要做的.
class Parent
{
protected function _doStuff();
}
class Child extends Parent
{
protected function _doChildStuff();
}
class Your_Class extends Child
{
// Access to all of Parent and all of Child's members
}
// Your_Class has access to both _doStuff() and _doChildStuff() by inheritance
Run Code Online (Sandbox Code Playgroud)
RRe*_*ser 10
正如所说的@morphles,这个功能将在php 5.4中作为特征(如其他语言中的mixins)提供.但是,如果真的需要,您可以使用这样的解决方法:
// your class #1
class A {
function smthA() { echo 'A'; }
}
// your class #2
class B {
function smthB() { echo 'B'; }
}
// composer class
class ComposeAB {
// list of implemented classes
private $classes = array('A', 'B');
// storage for objects of classes
private $objects = array();
// creating all objects
function __construct() {
foreach($this->classes as $className)
$this->objects[] = new $className;
}
// looking for class method in all the objects
function __call($method, $args) {
foreach($this->objects as $object) {
$callback = array($object, $method);
if(is_callable($callback))
return call_user_func_array($callback, $args);
}
}
}
$ab = new ComposeAB;
$ab->smthA();
$ab->smthB();
Run Code Online (Sandbox Code Playgroud)