【问题标题】:PHP: Declare interface incompatibilityPHP:声明接口不兼容
【发布时间】:2014-09-11 14:55:02
【问题描述】:

PHP 中有没有办法声明两个接口不兼容? 也就是说,要防止一个类同时实现它们?

最好不要创建无意义的虚拟方法..

【问题讨论】:

  • 两个接口到底是如何不兼容的?
  • 正如@Machavity 所说,接口只是合同,所以你不能这样做。您可以尝试通过 Abstract Class 实现一个调用“接口”(抽象)方法并在两个接口都存在时抛出异常的方法来实现它。

标签: php interface


【解决方案1】:

在接口内部没有任何方法可以做到这一点,因为接口实际上并没有实现,它只是定义。

您始终可以让您的实现使用ReflectionClass::implementsInterfaceclass_implements 进行此类测试,但听起来人们正在编写新类,这是根本问题。

【讨论】:

    【解决方案2】:

    唯一的方法是为两者添加一个同名的函数,但正如您所说..您不希望实现“无意义的虚拟方法”。

    在我看来,可能有更好的方法来解决您的问题;)

    【讨论】:

      【解决方案3】:

      @Machavity 和@Evert 是对的。拐杖:):

      trait Compatibility{
      private $incompatible_couples = array(
                               'Foo'=> array('A','C')
                             );
      
      public function checkInterfaces($classname){
         $class_interfaces = class_implements($classname);
         // array(3) { ["A"]=> string(1) "A" ["B"]=> string(1) "B" ["C"]=> string(1) "C" }
      
         $couple = $this->incompatible_couples[$classname];
         if (count($couple)==count(array_intersect($class_interfaces,$couple))){
             die('Error: interfaces '.implode(' and ',$couple).' are incompatible');
         }
       }
      }
      
      interface A{
       //...
       }
      
      interface B{
        //...
      }
      
      interface C{
        //...
      }
      
      class Foo implements A,B,C{
        use Compatibility; 
      
        function __construct(){
         self::checkInterfaces(__CLASS__); // checing interface compatibility
         //....
        }
      }
      
      var_dump(new Foo()); 
      // Error: interfaces A AND C are incompatible.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-08
        • 2016-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-02
        相关资源
        最近更新 更多