PHPStorm error with methods compatibility

I have a followed test-code…

interface I1
{

}

class C1 implements I1
{
    protected function f()
    {
        return 1;
    }
}

interface I2 extends I1
{
    public function f();
}

class C2 extends C1 implements I2
{
    public function f()
    {
        return parent::f();
    }
}

interface I3 extends I2
{

}

class C3 extends C2 implements I3
{

}

echo (new C3)->f();

It works fine. But my PHPStorm code inspection means error over “C3 extends C2”:

Declaration of ‘C1->f()’ must be compatible with ‘I2->f()’, access must be public

I think, this is not PHP itself, but PHPStorm problem. Could I fix it?

PHPStorm is probably getting tripped up by the function f being given the same name in C1 and C2.

If you think about it it doesn’t make sense for C1::f to be called the same thing as C2::f, as C1::f is supposed to be called internally by the class, but C2::f is supposed to be called publicly by something else.

The fix is simple: don’t do this.

Anytime you start mixing up function and interface names with multiple extends then you are just asking for trouble. Interfaces have their place but keep things simple.

On the positive side, at least you didn’t throw any traits into your example.

Sorry, I just doesn’t completely understood… What exactly should I avoid in my code? No interfaces and than no Dependency Injection - that is clear. Also no traits. What’s more?.. No method overriding? No class extensions? No classes at all, functions only?..

So, my friend, I need no any recommendation, how should I build my code architecture, clear? I asked for some problem. If you’ve got no answer to my question, just say nothing.

Start by adopting some useful naming conventions. Names like I1,I2,I3,C1,C2,C3 and f are not particularly descriptive.

Ah but they are just example names right? You don’t really use names like that in your code? Which is kind of my point. You are asking for help to avoid what appears to be an unexpected PHPStorm error. Great.

Provide a real example which shows why you actually have this clever extending going on and maybe an alternative could be provided. Use actual class, interface and method names and show why you came up with that particular structure.

The notion of I3 extends I2 which extends I1 is just silly code. It would require a very very very special and extremely unusual use case to justify.

1 Like