如何获取常量的值并将其保存到数据库

How to get the value of a constant and save it to the database

我有一个常量 class 就像这样

Class MyConstants
{
const TEST = "asd";
const TEST123 = "foo";
const TEST333 = "fooBar";
const TEST321 = "bar";
}

在我的控制器中,我得到了所有常量和随机的 select 3,问题是我只从常量中得到了键,但我需要值

$allConstants = $this->getAllConstants();
$foo = array_rand($allConstants, 3);

dd($foo)

 array:3 [
  0 => "TEST321"
  1 => "TES"
  2 => "TEST123"
 ]

我怎样才能得到常量的值,例如 foobar ?

然后我还需要将它们保存到数据库中。我应该循环遍历它们吗?

$fooBarEntity->setData($foo);

感谢您的帮助。

array_flip 交换所有键及其在数组中的关联值。 试试这个:

Class MyConstants
{
    const TEST = "asd";
    const TEST123 = "foo";
    const TEST333 = "fooBar";
    const TEST321 = "bar";
}

$reflection = new ReflectionClass(MyConstants::class);
$values = $reflection->getConstants();
$data = array_rand(array_flip($values), 3);
foreach($data as $item) {
    #$fooBarEntity->setData($item);
}
print_r($data);