PHP 中的多重扩展

发布于 2024-11-03 05:24:26 字数 107 浏览 1 评论 0原文

我听说不能使用两次扩展。

我有两个类:

Base32 和 SecureRandom

TOTP 需要的

。我怎样才能同时使用这两个呢?

I've heard that you can't use extend twice.

I have two classes:

Base32 and SecureRandom

Which I need for TOTP.

How can I use both of these for it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一个人的旅程 2024-11-10 05:24:26

使用接口composition(包括其中一个类的实例作为该类的成员变量)。

接口允许您定义类中方法的原型。然后,类实现该接口,并且必须为接口中的每个原型定义一个方法。您只能直接从一个类继承(扩展),但可以实现任意数量的接口。

如果您发现界面不太适合您的任务,只需使用组合即可。

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. You can only inherit directly from one class (extends) but you can implements an arbitrary number of interfaces.

If you find that interfaces don't fit your task well, just use composition.

瀞厅☆埖开 2024-11-10 05:24:26

看看PHP5.4 Traits,它们解决了多重扩展的问题。

将它们与接口结合起来以获得 instanceof 功能。

例如:

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); 
}

结果将是:

object(Shop)[1]
  protected 'client' => string 'test' (length=4)

Take a look into PHP5.4 Traits they kind of solving problem of multiple extends.

Combine them with interfaces to get instanceof functionality.

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)
决绝 2024-11-10 05:24:26

PHP 不允许多重继承。您需要扩展其中一个并将另一个作为私有变量或类似的变量。

PHP doesn't allow for multiple inheritance. You'll need to extend one of them and have the other as a private variable, or something like that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文