phpenumsstatic

Accessing PHP's enum's 'value' property statically


Suppose a PHP trait that looks like this;

trait Accessor
    {
        public static function int():int
        {
            return self::value;
        }
    }

and an enum to go with it;

enum Titular: int
    {
        use Accessor;

        case minimus=1;
        case maximus=2;
    }

What would the implementation be for the int() method to return the value of the current enum, like so?

Titular::minimus::int(); //1

Enum's 'value' property cannot be accessed statically like that: self::value. This I believe is well known. Trying to do so produces a fatal error

Fatal error: Uncaught Error: Undefined constant Titular::value in .... Non-static properties cannot be accessed statically.

Demo: https://3v4l.org/CHnao

Am hoping for some implementation that would return the value through a static method.


Solution

  • use this

    public function int(): int # remove static 
    {
        return $this->value;
    }
    

    You can call

    echo Titular::minimus->int(); # 1
    

    Static methods belong to the class itself, not to any instance