是否可以使用变量名定义常量? [关闭]

I want to be able to generate some constants from an array. So something like this:

foreach ($array as $key => $value) {
    define($key,$value);
}

Is there a simple way to do this?

You're already doing this in your code. Or d you mean like this?

$array = array("sparkles" => "pretty");

foreach($array as $key=>$value) {
    ${$key} = $value;
}

echo $sparkles; //pretty

Also you can try to use extract function. It produces the same result (almost) as in njk's answer

See: http://php.net/manual/en/function.extract.php

An alternative, if you have many constants to define, and APC installed:

$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);

(straight example from apc_define_constants)


Edit: an interesting read about performance

Assuming PHP 5.3 or higher, you could do:

array_walk($array, function ($value, $key) { 
    define($key, $value);
});

or

array_walk(array_flip($array), 'define');

But honestly, I would just use your current method.