【问题标题】:How many interfaces can a class implement in PHP?PHP 中一个类可以实现多少个接口?
【发布时间】:2015-04-11 20:55:44
【问题描述】:

我正在寻找一个不难的问题的答案,但我不知道一个类可以实现多少个接口。

这可能吗?

class Class1 implements Interface1, Interface2, Interface3, Interface4 {
   .....
}

对于我找到的所有类似示例,我发现一个类只能实现 2 个接口。但是没有任何关于我要查找的信息。

【问题讨论】:

  • 只要这些接口中没有冲突的方法名称,我相信没有实际限制。

标签: php oop interface implements


【解决方案1】:

一个类可以实现的接口数量在逻辑上没有限制。

【讨论】:

    【解决方案2】:

    您可以实现的接口数量没有限制。根据定义,你只能extend(继承)一个类。

    实际上,我会限制你实现的接口的数量,以免你的类变得过于庞大而难以使用。

    【讨论】:

    • 所以你是说,这种方式可行吗? class Class1 implements Interface1, Interface2, Interface3, Interface4{
    • 我认为实现数千个接口没有问题。它使工作更轻松。
    • @ArnasPečelis 正确。你也可以命名你的接口
    • 其实有一个限制:memory_limit
    • @YoushaAleayoub 虽然在技术上是正确的(分配太多并且 PHP 崩溃),但这不是编程限制,而是更多的困难
    【解决方案3】:

    我写了一个脚本来证明以上陈述(数量不限):

    <?php
    
    $inters_string = '';
    
    $interfaces_to_generate = 9999;
    
    for($i=0; $i <= $interfaces_to_generate; $i++) {
      $cur_inter = 'inter'.$i;
      $inters[] = $cur_inter;
      $inters_string .= sprintf('interface %s {} ', $cur_inter);
    }
    
    eval($inters_string); // creates all the interfaces due the eval (executing a string as code)
    
    eval(sprintf('class Bar implements %s {}', implode(',',$inters))); // generates the class that implements all that interfaces which were created before
    
    $quxx = new Bar();
    
    print_r(class_implements($quxx));
    

    您可以修改 for 循环中的计数器变量,以使该脚本生成更多接口以由“Bar”类实现。

    它可以轻松地与多达 9999 个接口(显然更多)一起工作,正如您在执行该脚本时从最后一个代码行 (print_r) 的输出中看到的那样。

    计算机的内存似乎是接口数量的唯一限制,因为当数量太高时会出现内存耗尽错误

    【讨论】:

    • 感谢您提供了很好的示例,内存实际上不是这个问题。
    【解决方案4】:

    你可以实现任意多个类,没有限制。

    class Class1 implements Interface1, Interface2, Interface3, Interface4, Interface5, Interface6{
       .....
    } 
    

    这意味着这是正确的 希望对你有帮助

    【讨论】:

      【解决方案5】:

      是的,一个类可以实现两个以上的接口。
      来自PHP manual:

      如果需要,类可以通过分隔实现多个接口 每个接口都用逗号。

      【讨论】:

        猜你喜欢
        • 2012-06-17
        • 1970-01-01
        • 2013-05-24
        • 2014-02-11
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        • 2010-10-13
        • 1970-01-01
        相关资源
        最近更新 更多