问题描述
如果我有几个具有我需要的功能的类,但想单独存储以供组织使用,我可以扩展一个类以同时拥有这两个功能吗?
If I have several classes with functions that I need but want to store separately for organisation, can I extend a class to have both?
即class a extends b extends c
我知道如何一次扩展一个类,但我正在寻找一种方法来使用多个基类立即扩展一个类 - AFAIK 你不能在 PHP 中做到这一点,但应该有办法解决它不诉诸class c extends b
,class b extends a
edit: I know how to extend classes one at a time, but I'm looking for a method to instantly extend a class using multiple base classes - AFAIK you can't do this in PHP but there should be ways around it without resorting to class c extends b
, class b extends a
推荐答案
如果你真的想在 PHP 5.3 中伪造多重继承,你可以使用魔术函数 __call().
If you really want to fake multiple inheritance in PHP 5.3, you can use the magic function __call().
虽然从 A 类用户的角度来看,这很丑陋:
This is ugly though it works from class A user's point of view :
class B {
public function method_from_b($s) {
echo $s;
}
}
class C {
public function method_from_c($s) {
echo $s;
}
}
class A extends B
{
private $c;
public function __construct()
{
$this->c = new C;
}
// fake "extends C" using magic function
public function __call($method, $args)
{
$this->c->$method($args[0]);
}
}
$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");
打印abcdef"
这篇关于我可以在 PHP 中使用 1 个以上的类来扩展一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!