我可以在PHP中使用多于一个类来扩展类吗?

编程入门 行业动态 更新时间:2024-10-17 09:52:50
本文介绍了我可以在PHP中使用多于一个类来扩展类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有几个类,我需要的功能,但想要分开存储组织,我可以扩展一个类有两个?

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中使用多于一个类来扩展类吗?

本文发布于:2023-08-01 12:35:27,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!