Reputation: 452
I'm reading the php enum documents and from what I understand, this new feature in its most basic form is for us to set constants to be used in classes for type checking.
Is there any way to work with classes? Example:
enum ClassEnum {
case \App\Model\Test;
case \App\Model\AnotherTest;
}
Upvotes: 0
Views: 1208
Reputation: 32252
No, you can't use Enums like that. But there are a couple alternatives.
First and foremost would be to use an interface, which sets the contract for what methods an implementation must expose, and what methods other code can expect to use to interact with it.
interface FooInterface {
public function doThing();
}
class Foo implements FooInterface {
public function doThing() {
printf("%s: thing!\n", __CLASS__);
}
}
class Bar implements FooInterface {
public function doThing() {
printf("%s: thing!\n", __CLASS__);
}
}
class InterfaceTest {
public function __construct(FooInterface $obj) {
$obj->doThing();
}
}
$t1 = new InterfaceTest(new Foo());
$t2 = new InterfaceTest(new Bar());
In the rare case that you want to use multiple, non-extending types you can also use Composite Types which were introduced in PHP 8:
class CompositeTest {
public function __construct(Foo|Bar $obj) {
$obj->doThing();
}
}
$c1 = new CompositeTest(new Foo());
$c2 = new CompositeTest(new Bar());
Both of the above snippets will output:
Foo: thing!
Bar: thing!
But I far and away recommend using Interfaces as it makes your code more flexible and easier to write and maintain.
Upvotes: 1