PHP interface implementation rejects subclasses by parameters

consider this:

class A{}

class B extends A{}

interface I{
 // expects object instanceof A
 function doSomething(A $a);
}

class C implements I
{
 // fails ????
 function doSomething(B $b){}
}

In my concept, the above should work, but it's not like php rejects this implementation, requiring the first parameter to be of exactly the same type (A) as defined in interface (I). Since B is a subclass of A, I don't see what the problem is. Did I miss something?

+3
source share
2 answers

class C implements Imeans that there must be a subtype relation between Cand I. This means that a type object Cshould be used wherever a type object is required I.

C , I, doSomething - I.doSomething A, C.doSomething A

, C.doSomething, A, B. B, .

( , ). , .

+5

( , ). .

- instanceof :

class A{}

class B extends A{}

interface I{
 // expects object instanceof A
 function doSomething(A $a);
}

class C implements I
{

 function doSomething(A $b){
   if($b is instance of B){
   //do something
   }else{throw new InvalidArgumentException("arg must be instance of B") };
 }
}
+2

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


All Articles