I wanted to make an interface in PHP, but I didn't want it to be too restrictive on what argument type it would accept in one of the public methods. I didn't want to do
interface myInterface {
public function a( myClass $a);
}
Because I may not want to pass it an instance of myClass. But, I do want to make sure that the object passed conforms to certain parameters, which I could accomplish by defining an interface. So I thought to specify classes that use interfaces, like so:
<?php
interface iA {}
interface iB {}
interface iC {
public function takes_a( iA $a );
public function takes_b( iB $b );
}
class apple implements iA {}
class bananna implements iB {}
class obj implements iC {
public function takes_a( apple $a ) {}
public function takes_b( bananna $b ) {}
}
But, I get the error PHP Fatal error: Declaration of obj::takes_a() must be compatible with iC::takes_a(iA $a) on line 15
Is there a way ensure that an argument accepts only a class of a certain interface? Or perhaps am I overthinking/over-engineering this?
public function takes_a( iA $a);in your obj class) but you can pass apple on this instance.$o = new obj(); $o->takes_a(new apple());takes_a()to only allow "apple"s you disallow other "iA"s, but the interface iC demands to accept any iA as a parameter.