如果我有一个包含嵌套变量的变量,例如:
$message = "Hello $user_name, an email was send to $user_email ...";
$user_name = 'User Name';
$user_email = 'user@email.com';
是否可以产生如下输出:
Hello User Name, an email was send to user@email.com ...
没有打电话给eval()
?
答案 0 :(得分:2)
是的,可以将变量$user_name
和$message
置于$user_email = 'user@email.com';
$user_name = 'User Name';
$message = "Hello $user_name, an email was send to $user_email ...";
echo $message; //Will output: Hello User Name, an email was send to user@email.com ...
之上,以便首先实例化它们。
$message = function($name = null, $email = null){
return "Hello $name, an email was send to $email ...";
};
$user_name = 'User Name';
$user_email = 'user@email.com';
$newMessage = $message($user_name, $user_email);
编辑:阅读完反应后,您可以使用闭包,例如:
file.seek(0)
答案 1 :(得分:1)
您可以'定义'占位符并将其替换为您需要的位置。
$message = "Hello #user_name#, an email was send to #user_email# ...";
$user_name = 'User Name';
$user_email = 'user@email.com';
$newMessage = str_replace(array("#user_name#", "#user_email#"), array($user_name, $user_email), $message);
请参阅str_replace以供参考。
答案 2 :(得分:1)
$message = "Hello %s, an email was send to %s ...";
$user_name = 'User Name';
$user_email = 'user@email.com';
echo sprintf($message, $user_name, $user_email);
或
printf($message, $user_name, $user_email);
答案 3 :(得分:0)
$user_email = 'user@email.com';
$user_name = 'User Name';
$message = "Hello " . $user_name . ", an email was send to " . $user_email . " ...";