PHP: yes, it's possible
spO0q
Posted on June 22, 2024
Let's see if that's possible, then we'll see when to use it.
Is is possible?
Can enumerations implement interfaces?
Yes.
Is it possible to "Multi catch" in PHP?
Yes.
Instead of doing that:
try {
} catch(MyException $e) {
} catch(AnotherException $e) {
}
Do that:
try {
} catch(MyException | AnotherException $e) {
}
Can an interface extend another interface?
Yes.
Unlike with classes, you can even have multiple inheritance:
interface A
{
public function foo();
}
interface B
{
public function bar();
}
interface C extends A, B
{
public function baz();
}
Do you need it?
Does your enum need an interface?
It's usually a good practice, as you can type check for that interface quite conveniently:
interface Colorful {
public function color(): string;
}
enum Suit implements Colorful {
case Hearts;
case Diamonds;
case Clubs;
case Spades;
public function color(): string {
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
function paint(Colorful $c) { ... }
paint(Suit::Clubs);
Do you need Multi catch blocks?
It depends.
This syntax works:
try {
} catch(MyException | AnotherException $e) {
echo $e->getMessage();
}
However, ensure your exceptions implement the same methods.
In contrast, using several catch blocks can be handy to catch different classes of exceptions.
Although, if you need to group your exceptions, avoid the following:
try {
} catch(AnException | AnotherException2 | AnotherException3 | AnotherException4 | AnotherException5 | AnotherException6 | AnotherException7 | AnotherException8 | AnotherException9 $e) {
echo $e->getMessage();
}
While it's valid, it can give the false impression of clean code. Having too much exceptions is not a good [de]sign.
Inheritance with interfaces
I must admit I rarely use that one, but it's good to know:
interface Writable
{
public function write();
}
interface Document extends Writable
{
public function edit();
}
Do you need it?
It depends. If your interface contains too much methods, it probably means you are breaking the Interface Segregation Principle.
Posted on June 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 10, 2024