【发布时间】:2021-12-16 02:41:43
【问题描述】:
<?php
// set a value for this example, but imagine the user
// was posting this in a form.
$_POST['var1'] = 'another_type';
$valueObj = new class($_POST['var1']) {
private $m_value;
public function __construct(string $input)
{
switch ($input)
{
case 'type1' : $this->m_value = 1; break;
case 'type2' : $this->m_value = 2; break;
case 'another_type' : $this->m_value = 3; break;
default : throw new Exception("Invalid input: $input");
}
}
public function getValue() : int { return $this->m_value; }
};
print $valueObj->getValue(); // 3
https://blog.programster.org/php7-0-anonymous-classes
我无法理解 $_POST['var1'] 在构造函数中是如何分配给 $m_value 的。
【问题讨论】: