Php eloquent enumeration
Anyone familiar with working with this library: https://github.com/eloquent/enumeration
I am having trouble converting an instance of a constant back to a constant value.
class TestEnum extends AbstractEnumeration
{
const THING1 = 'test1';
const THING2 = 'test2';
}
class DoStuff
{
public function action(TestEnum $test)
{
if($test === 'test1') {
echo 'THIS WORKS';
}
}
}
$enumTest = TestEnum::THING1();
$doStuff = new DoStuff();
$doStuff->action($enumTest);
My goal is to get the method action to print "IT WORKS". Since $ test is an instance of TestEnum, this will not be true.
+3
source to share
1 answer
You are close, but there are two problems:
- It matters.
Thing1
! =Thing1
-
$test
when viewed as a string, its key is calculatedThing1
. You want its meaning$test->value()
Example:
class TestEnum extends AbstractEnumeration
{
const THING1 = 'test1';
const THING2 = 'test2';
}
class DoStuff
{
public function action(TestEnum $test)
{
if($test->value() === 'test1') {
echo 'THIS WORKS';
}
}
}
$enumTest = TestEnum::THING1();
$doStuff = new DoStuff();
$doStuff->action($enumTest);
Output:
THIS WORKS
+2
source to share