Does a PHP interface accept an interface argument?

I wanted to create an interface in PHP, but I did not want it to be too strict regarding what type of argument it would accept in one of the public methods. I did not want to do

interface myInterface { public function a( myClass $a); } 

Because I do not want to pass an instance of myClass . But I want to make sure that the passed object matches certain parameters that I could fulfill by defining the interface. So I decided to specify classes that use interfaces, for example:

 <?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 an error message PHP Fatal error: Declaration of obj::takes_a() must be compatible with iC::takes_a(iA $a) on line 15

Is there a way to make sure that the argument accepts only the class of a specific interface? Or maybe I'm thinking too much about it?

+5
source share
1 answer

Your concept is absolutely correct. There is only one small wrong part. Class methods must have the same signature as specified in your interface.

as VolkerK said:

see wikipedia . By shortening take_a () to enable the apple, you deny other "iA", but the iC interface requires you to accept any iA parameter as a parameter. - VolkerK

with this in mind, see the revised code:

 <?php interface iA { function printtest(); } interface iB { function play(); } //since an interface only have public methods you shouldn't use the verb public interface iC { function takes_a( iA $a ); function takes_b( iB $b ); } class apple implements iA { public function printtest() { echo "print apple"; } } class bananna implements iB { public function play() { echo "play banana"; } } //the signatures of the functions which implement your interface must be the same as specified in your interface class obj implements iC { public function takes_a( iA $a ) { $a->printtest(); } public function takes_b( iB $b ) { $b->play(); } } $o = new obj(); $o->takes_a(new apple()); $o->takes_b(new bananna()); 
+3
source

Source: https://habr.com/ru/post/1233676/


All Articles