get*_*way 7 php conditional heredoc
我想知道你是否可以在heredocs中有条件语句,这是我的脚本,但它deosnt正确解析$ username?
php代码:
function doSomething($username) {
if (isset($_SESSION['u_name'])){
$reply ='<a class ="reply" href="viewtopic.php?replyto=@$username.&status_id=$id&reply_name=$username"> reply </a>';
return <<<ENDOFRETURN
$reply
ENDOFRETURN;
Run Code Online (Sandbox Code Playgroud)
这个问题是在html上呈现的$ username变量deosnt.它仍然是$ username :))谢谢
简单.用花括号包裹所有东西(显然在Heredocs中支持),然后使用匿名函数并返回逻辑所需的内容:]你甚至可以使用它并在heredocs中的匿名函数变量中使用表达式.
例:
// - ############# If statement + function to set #################
$result = function ($arg1 = false, $arg2 = false)
{
return 'function works';
};
$if = function ($condition, $true, $false) { return $condition ? $true : $false; };
// - ############# Setting Variables (also using heredoc) #########
$set = <<<HTML
bal blah dasdas<br/>
sdadssa
HTML;
$empty = <<<HTML
data is empty
HTML;
$var = 'setting the variable';
// - ############## The Heredoc ###################################
echo <<<HTML
<div style="padding-left: 34px; padding-bottom: 18px;font-size: 52px; color: #B0C218;">
{$if(isset($var), $set, $empty)}
<br/><br/>
{$result()}
</div>
HTML;
Run Code Online (Sandbox Code Playgroud)
你想在heredoc中有条件语句吗?或者你想知道为什么你的代码不起作用?因为目前你在heredoc里面没有条件声明,但无论如何都不可能.
如果你想知道为什么你的代码不起作用:
这与heredoc无关,这是因为整个$reply字符串用单引号括起来,其中不支持变量解析.使用字符串连接:
$reply ='<a class ="reply" href="viewtopic.php?replyto=@' . $username . '.&status_id=$id&reply_name=' . $username . '"> reply </a>'
Run Code Online (Sandbox Code Playgroud)
我希望你在真正的代码中用heredoc做更多的事情,否则return $reply会更容易;)(而你缺少括号).