1

Is there any way in PHP to declare that two interfaces are incompatible? That is, to prevent a class from implementing both of them at once?

Ideally without creating meaningless dummy methods ..

2
  • 2
    How exactly are two interfaces incompatible? Commented Sep 11, 2014 at 15:10
  • As @Machavity says, interfaces are just contracts, so you cannot do it. You could try to achieve it with an Abstract Class implementing a method that calls the "interfaced" (abstract) methods and throwing an exception if both interfaces exist. Commented Sep 11, 2014 at 15:40

3 Answers 3

2

There's not any way to do this inside an interface because the interface doesn't actually implement, it only defines.

You can always have your implementation do that kind of test using ReflectionClass::implementsInterface or class_implements, but it sounds like people are writing new classes and that's the root problem.

Sign up to request clarification or add additional context in comments.

Comments

1

The only way is to add a function with the same name to both, but as you said.. you prefer not to implement 'meaningless dummy methods'.

It sounds to me that there's probably a better way to solve your problem though ;)

Comments

1

@Machavity and @Evert are right. Crutch:):

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.