-1

Imagine a generic library defines a class:

class A_CLASS {
    public function foo(B_CLASS $b) {
        // Use $b as B_CLASS
    }
}
class B_CLASS {
}

And I need to override this one, but with my own child B_CLASS, so I would declare

class A_CHILD_CLASS extends A_CLASS {
    public function foo(B_CHILD_CLASS $b) {
        parent::foo($b);
        // Use $b as B_CHILD_CLASS
    }
}
class B_CHILD_CLASS extends B_CLASS {
}

This is not working on PHP 5.6. In other languages, this will work, and we could also use a generic interface. But in PHP, this is not available and there is no generic interface.

So, how could I implement it in PHP ? This is really a problem in my project.

tereško
  • 58,060
  • 25
  • 98
  • 150
Loenix
  • 1,057
  • 1
  • 10
  • 23

1 Answers1

2

The reason for this error:

Declaration of A_CHILD_CLASS::foo() should be compatible with A_CLASS::foo(B_CLASS $b)

is that you are trying to override the foo() function but with different arguments. As far as I know this is called overloading which isn't supported by PHP. (while there are some patches to bypass it)

Therefore, the solution should be to modify this function:

public function foo(B_CHILD_CLASS $b)

To:

public function foo(B_CLASS $b)

And to find a different way to achieve what's you're looking for. Consider removing the declaration of the argument's type.

public function foo($b)

Further reading:

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39