Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Eloquent Enumeration

Is anyone familiar with working with this library: https://github.com/eloquent/enumeration

I am having trouble converting the instance of the constant back to the 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 have the method action print 'THIS WORKS'. Because $test is an instance of TestEnum, this would not evaluate to true.

like image 772
theamycode Avatar asked Mar 26 '26 17:03

theamycode


1 Answers

You're close, but there are two problems:

  1. Case matters. Thing1 != THING1
  2. $test, when treated as a string, evaluates to its key THING1. You want its value $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
like image 153
user3942918 Avatar answered Mar 29 '26 06:03

user3942918



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!