0

My Visual Studio Code shows "undefined method". I want to know is it possible to "fix" it with some VSC settings or maybe there is a PHP solution. I have this

class A
{
    public function someMethodA()
    {
        // ...
    }
}

class B extends A implements Bint
{
    public function someMethodB()
    {
        // ...
    }
}

interface BInt
{
    public function someMethodB();
}

class C
{
    public function someMethodC(Bint $b)
    {
        // VSC shows indefined method
        return $b->someMethodA();
    }
}

My interface doesn't have someMethodA, is it possible to "inherit" it from Class A to get rid of "error"? This class comes from a package, it has no interface and I need to extend it

getStatusCode() exists, it is public, everything works, but Visual Studio Code cannot understand it

enter image description here

IMSoP
  • 89,526
  • 13
  • 117
  • 169
Ihar Aliakseyenka
  • 9,587
  • 4
  • 28
  • 38
  • 1
    You have two different examples here. In your first example, the IDE is correct, the variable `$b` *might not* have `someMethodA`; in the second example (the image), you haven't actually shown the interface, but there is more complicated code in the method which may be relevant to the question. Please [edit] to make sure you include the code you're actually interested in, as code and not images. – IMSoP May 14 '22 at 17:47
  • @IMSoP Hi there, my question is exactly about **might not have** but it definitely has (because of parent class A). Interface however doesn't have this method (that is why IDE showing this error). Should I import all methods from parent A (I have no control over it) into interface or there some elegant solution for this? The code is correct, I can edit, but it is will be irrelevant data in my opinion. Image is just for showing type of error to understand – Ihar Aliakseyenka May 14 '22 at 18:03

1 Answers1

1

Focussing on your code example, not your screenshot, your IDE is correct, and you should listen to what it's telling you.

The contract of method someMethodC is that it can accept any implementation of interface Bint. That guarantees that you can call someMethodB, but does not guarantee anything else.

If the method is passed an instance of class A, then PHP will allow you to call someMethodA on it, but it might be passed some other object, such as:

class OnlyB implements Bint {
    public function someMethodB() {
        // ..
    }
}

The contract (signature) of someMethodC says you can pass this object, but when you call someMethodA, you will get an error.

If you want the method to always receive instances of class A, say so in the signature:

public function someMethodC(A $b) {
    return $b->someMethodA();
}

If you want it to accept any implementation of Bint, then you should only call methods guaranteed to exist by that interface.

IMSoP
  • 89,526
  • 13
  • 117
  • 169