Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading