如果您确定数据库中的变量是安全的(只有您可以更改它们),您可以像这样评估 get 变量函数中的代码:
function get_variable($var, $data = array())
{
// Here the code that gets the variable from the database
$db_var = 'I like $fruit';
extract($data);
$return = '';
eval('$return = "' . $db_var . '"');
return $return;
}
// And then use this in the controller:
$details['test'] = get_variable('my_variable_name', $details);
但是当其他人可以访问数据库变量时,您真的不想使用 eval (真的不要!)。而是使用某种形式的模板,例如“我喜欢 %fruit%”,并使 get_variable 看起来像这样:
function get_variable($var, $data = array())
{
// Here the code that gets the variable from the database
$db_var = 'I like $fruit';
extract($data);
$return = $db_var;
foreach($data as $var => $value) {
$return = str_replace('%'.$var.'%', $value, $return);
}
return $return;
}
// And then use the same method in the controller:
$details['test'] = get_variable('my_variable_name', $details); // This makes all variables in details available in the database variable