我正在尝试遍历包含 SplEnum 的 PHP 类中的变量。它不起作用。这是代码:
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";
}
这是输出:
[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
似乎正在发生的事情是 foreach
循环试图将每个类变量变成一个 enum
。如何正确地遍历类中的变量?
最佳答案
众所周知,SPL Lib 存在问题。
您可以将变量声明的顺序切换为
public $variable = 2;
public $enum;
这个例子会起作用。
如果您完全删除 enum
属性声明,它也会起作用。
class fruit
{
public $variable = 2;
public function __construct(enum $enum)
{
$this->enum = $enum;
}
}
也许您最好的选择是避免它,或者将其保密/保护。
关于php - 涉及 SplEnum 时遍历 PHP 类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35454628/