[英]Multiple Extends in PHP
I've heard that you can't use extend twice. 我听说您不能两次使用扩展。
I have two classes: 我有两节课:
Base32 and SecureRandom Base32和SecureRandom
Which I need for TOTP. 我需要TOTP。
How can I use both of these for it? 我怎样才能同时使用它们呢?
Use interfaces or composition (include an instance of one of the classes as a member variable of the class). 使用接口或组合 (包括其中一个类的实例作为该类的成员变量)。
Interfaces allow you to define prototypes for the methods in a class. 接口允许您为类中的方法定义原型。 A class then implements
that interface and must define a method for each prototype in the interface. 然后,一个类将implements
该接口,并且必须为接口中的每个原型定义一个方法。 You can only inherit directly from one class ( extends
) but you can implements
an arbitrary number of interfaces. 您只能直接从一个类( extends
)继承,但可以implements
任意数量的接口。
If you find that interfaces don't fit your task well, just use composition. 如果发现接口不适合您的任务,请使用合成。
Take a look into PHP5.4 Traits they kind of solving problem of multiple extends. 看一下PHP5.4特性,他们解决了多种扩展问题。
Combine them with interfaces to get instanceof functionality. 将它们与接口结合起来以获得instanceof功能。
For example: 例如:
interface ClientAwareInterface {
public function setClient($client);
}
trait ClientAwareTrait {
protected $client;
public function setClient($client)
{
$this->client = $client;
}
}
class Shop implements ClientAwareInterface extends SomeClass {
use ClientAwareTrait; // use our trait to implement interface methods
use OtherTrait;
}
$shop = new Shop();
if($shop instanceof ClientAwareInterface) {
$shop->setClient('test');
var_dump($shop);
}
Result would be: 结果将是:
object(Shop)[1]
protected 'client' => string 'test' (length=4)
PHP doesn't allow for multiple inheritance. PHP不允许多重继承。 You'll need to extend one of them and have the other as a private variable, or something like that. 您需要扩展它们中的一个,并将另一个作为私有变量或类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.