Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface with no parameters

Tags:

php

I have a question about interfaces. Can I have an interface specify a method with no parameters, but still have parameters in the class?

interface FooInterface {
    public function bar();
}

class Foo implements FooInterface {
    public function bar($parameters = array())
    {
        return 'bar';
    }
}

I don't get an error doing this locally in PHP 5.5.10, but do in PHP 5.4.0.

like image 377
veroarts Avatar asked Aug 20 '14 04:08

veroarts


People also ask

Which functional interface does not take any inputs?

The Supplier functional interface does not take any inputs, while the Consumer functional interface does not return any data. This behavior extends to the primitive versions of the functional interfaces, making Option C the correct answer.

Can functional interface have no methods?

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.

Which functional interface does not return a value?

Consumer. The Java Consumer interface is a functional interface that represents an function that consumes a value without returning any value.

Which functional interface does not take any input and returns and output?

java - functional interface that takes nothing and returns nothing - Stack Overflow.


Video Answer


1 Answers

The problem is that the declaration of the bar method in the Foo class is actually not compatible with the declaration in FooInterface.

FooInterface::bar is a method with no parameters, Foo::bar has one parameter (though an optional one). This throws an exception in earlier PHP 5.4.x versions.

Apparently, in later versions the PHP devs have decided that it's ok to declare a method with more parameters than the interface or parent class, as long as the parameters are optional.

EDIT:

The PHP documentation states:

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.

So the behaviour you're experiencing appears to be a bug in earlier versions of PHP. Unfortunately, I was not able to find a bug report or release note which would indicate when, and for which PHP versions, the bug was fixed.

The lowest version I could test on right now was PHP 5.4.9, and the bug appears to be fixed there, as I could run the code without errors.

like image 90
lxg Avatar answered Oct 20 '22 02:10

lxg