Get Off My Lawn
Get Off My Lawn

Reputation: 36351

method must be compatible with interface method

I have an interface that defines a method charge(), the first parameter is required and the second one is optional, and my layout looks something like this:

interface Process{

    public function charge($customerProfileId, $paymentProfileId = null);

    // Other items

}

abstract class CardProcessor implements Process{

    // Some methods & properties are here

}

class Authorize extends CardProcessor{

    public function charge($customerProfileId, $paymentProfileId){
        // Process the card on profile
    }

}

When I load the file (even when I am not executing charge()) I get the following error:

PHP Fatal error: Declaration of src\processors\CardProcessors\Authorize::charge() must be compatible with src\interfaces\Process::charge($customerProfileId, $paymentProfileId = NULL) in /home/processor/src/processors/CardProcessors/Authorize.php on line 19"

What is the reason for this? It looks right to me...

Upvotes: 0

Views: 1442

Answers (2)

Adam T
Adam T

Reputation: 675

interface Process
{    
    public function charge($customerProfileId, $paymentProfileId);   
    // Other items
}

abstract class CardProcessor implements Process 
{   
    // Some methods & properties are here
    public abstract function charge($customerProfileId, $paymentProfileId);
}

class Authorize extends CardProcessor 
{    
    public function charge($customerProfileId, $paymentProfileId = null)
    {
        // Process the card on profile
    }    
}
  • Added method signature to abstract class CardProcessor as suggested by @Dev Mode
  • Took implementation out of interface ( var = null ) and put it in the concrete class.

Upvotes: 2

Elliot Rodriguez
Elliot Rodriguez

Reputation: 618

The signature for the charge method in your child class still has to match based on the original signature in the interface. It looks to me like your hierarchy still requires the matching signature.

From: PHP

Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.

In addition, from PHP Object Interfaces

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

Upvotes: 2

Related Questions