你能把PHP文本变成一个变量吗?
问题描述:
I was wondering if it was possible to dynamically create variables like so:
$sender = $email = $number = $message = "";
foreach ($_POST as $key => $value) {
if isset & !empty //loosely typed
$+key = $value // can something like this be done?
}
if so how?
答
PHP does have variable variables, but you don't need that here. I think a simple associative array or object will work just fine for you.
$data = array(
'sender' => 'Someone',
'email' => 'test@example.com',
'number' => 12345,
'message' => 'some message'
);
echo $data['sender']; // Someone
答
Something like this should work. But I wouldn't do it unless you completely trust the data and if its POST data then access it like $_POST['key']
foreach ($_POST as $key => $value) {
if isset & !empty //loosely typed
${$key} = $value // can something like this be done?
}
答
There is a PHP function called extract
which does what you are looking for.