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 ..
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 ..
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.
@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.