Given:
enum TestEnum: string
{
case CASE_1 = "first case";
case CASE_2 = "Second case";
}
This is supposed to return true
:
TestEnum::class instanceof BackedEnum
But I get false
I tried the following from this post (it fails to run in Laravel Tinker REPL, but runs as a script?):
interface TestEnumInterface extends BackedEnum
{
public function foo(): string;
}
enum TestEnum: string implements TestEnumInterface
{
case CASE_1 = 'case 1';
case CASE_2 = 'case 2';
public function foo(): string
{
return 'bar';
}
}
TestEnum::class instanceof BackedEnum //false
TestEnum::class instanceof TestEnumInterface //false
What am I missing?
Running PHP v8.1.13
Thanks
UPDATE:
Indeed, as per SomeOne1 reply, the following returns true:
TestEnum::CASE_1 instanceof BackedEnum
Then I’ll try to be more specific.
I have to test a variable $list
which could be a number of different enums (like $list = TestEnum::class
or $list = AnotherEnum::class
), or a Laravel collection, or an array.
//if ($list instanceof BackedEnum) {
if (isset($isEnum)) { // I want to get rid of this
// do stuff
}
else if ($list instanceof IlluminateDatabaseEloquentCollection || $list instanceof IlluminateSupportCollection) {
// do stuff differently
}
else if (is_array($list)) {
// do stuff differently
}
else {
var_dump($list);
dd('invalid list');
}
Then how can I test if this variable is of enum type?
2
Answers
solution:
tests:
TestEnum::class is not an instanceof an object, it is an ‘instanceof’ a string.
TestEnum::CASE_1 is instanceof of TestEnum or TestEnumInterface