PHP interfaces and optional parameters
Interfaces in object-oriented languages like Java, C# and PHP are useful language constructs for ensuring that objects will respond to certain methods. However, unlike Java and C# (until recently), PHP has optional parameters. As it turns out, this feature has an interesting (and a little bit unexpected) effect on how we can implement interfaces in PHP.
Consider a simple interface for making objects comparable:
interface IComparable {
public function compareTo($object);
}
Normally, in Java and C# (before 4.0) the only way to implement this interface would be to make a carbon copy of the method signature (save for the name of the parameter) and then fill in the method body.
class NetString implements IComparable {
public function compareTo($object) {
...
}
}
This satisfies the interface requirements because we need to have a method that responds to a method named compareTo
with a single argument. However, things get interesting when we introduce optional parameters. That's because we can write a method signature that is different from that found in the interface but still satisfies the requirement that the method have the correct name and accept only 1 parameter.
How is that possible? Well, imagine we wanted our NetString class to optionally ignore case when comparing:
class NetString implements IComparable {
public function compareTo($object, $ignoreCase = false) {
...
}
}
Notice how we slipped in another (optional) argument $ignoreCase
? Does this code still satisfy the IComparable interface? Absolutely. Why? Because we can still call compareTo($object)
in a meaningful way, and that's all the matters.
4 comments