Iterate over PHP class variables when using SplEnum

I am trying to iterate through variables in a PHP class that contains SplEnum. This does not work. Here is the code:   

class enum extends SplEnum { const First = 1; }

class fruit
{
    public $enum;
    public $variable = 2;
    public function __construct(enum $enum)
    {
        $this->enum = $enum;
    }
}

$apple = new fruit(new enum(enum::First));
foreach ($apple as $key => $value) {
    echo "[$key] => $value\n";
}

This is the conclusion:

[enum] => 1
PHP Fatal error:  Uncaught exception 'UnexpectedValueException' with message 'Value not a const in enum enum' in /home/test.php:16
Stack trace:
#0 /home/test.php(16): unknown()
#1 {main}
  thrown in /home/test.php on line 16

It seems that what happens is that the loop is foreachtrying to turn every class variable into enum. How to iterate over variables in a class?

+4
source share
1 answer

SPL Lib is known to be a bug.
You can switch the variable declaration order to

public $variable = 2;
public $enum;

And the example will work. It will also work if you completely delete the property declaration enum.

class fruit
{
    public $variable = 2;
    public function __construct(enum $enum)
    {
        $this->enum = $enum;
    }
}

, - /.

+2

Source: https://habr.com/ru/post/1629156/


All Articles