如果我有几个类,我需要的功能,但想要分开存储组织,我可以扩展一个类有两个?
class a extends b extends c
编辑:我知道如何一次扩展一个类, m寻找一个方法来立即扩展一个类使用多个基类 - AFAIK你不能这样做在PHP,但应该有办法,而不求助于 class c extends b p>
如果你真的想假冒多重继承,你可以使用魔术函数__call()。
这是丑陋的虽然它从A类用户的角度来工作:
class B { public function method_from_b($ s){ echo $ s; } } class C { public function method_from_c($ s){ echo $ s; } } A类扩展B { private $ c; public function __construct() { $ this-> c = new C; } //使用魔术函数fakeextends C public function __call($ method,$ args) { $ this-> ; c-> $ method($ args [0]); } } $ a = new A; $ a-> method_from_b(abc); $ a-> method_from_c(def);列印「abcdef」
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?
i.e. class a extends b extends c
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
解决方案Answering your edit :
If you really want to fake multiple inheritance, you can use the magic function __call().
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");Prints "abcdef"
更多推荐
我可以在PHP中使用多于一个类来扩展类吗?
发布评论