Fatal error: Declaration of .. must be compatible with .. PHP

The declaration of a public function in a sub class must match that of its parent:

public function addToCart();
public function addToCart( Product $product)

You cannot add a parameter to the signature.

This is closely related to the Liskov substitution principle.


Ishoppingcart::addToCart() states that the method does not take any parameter, while the implementation Shoppingcart::addToCart(Product $product) requires that a parameter of type Product must be passed into the method. This means that both declarations are incompatible and while the implemented interface must be satisfied PHP throws the shown error.

Solution would be to either change Ishoppingcart::addToCart() to Ishoppingcart::addToCart(Product $product) so that it requires a parameter of type Product or to change Shoppingcart::addToCart(Product $product) to allow no parameter to passed into the method: Shoppingcart::addToCart(Product $product = null);

The correct way depends on your application requirements.


Interface Ishoppingcart seems to define addToShoppingCart without parameters, but class Shoppingcart defines the same function taking Product as a parameter. I suppose the method in the interface should take Product as a parameter as well.