Conditional statements in php heredocs syntax?

I was wondering if you can have conditional statuses inside heredocs, this is my script, but it deosnt correctly parsed $ username?

php code:

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;

the problem with this is the $ username variable that deosnt gets in html. it remains $ username :)) thanks

+3
source share
3 answers

Do you want to have conditional statements in heredoc or are you wondering why your code is not working? Since you currently do not have a conditional statement inside the heredoc, but this is still not possible.

, :
heredoc, $reply , . :

$reply ='<a class ="reply" href="viewtopic.php?replyto=@' . $username . '.&status_id=$id&reply_name=' . $username . '"> reply </a>'

, heredoc , return $reply ;) ( ).

+6

. (, 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;
+4

, . "" heredoc, heredocs.

heredoc. , heredoc 3 . . heredoc . , , , , heredoc, , , . , , .

function doSomething($username = '', $status_id = '') {

  if ('' != $username && '' != $status_id) {

    $reply = <<<EOT
<a class ="reply" href="viewtopic.php?replyto=@{$username}&status_id={$status_id}&reply_name={$username}"> reply </a>

EOT;

  } else {

    $reply = <<<EOT
<h2>The username was not set!</h2>

EOT;

  }

  return $reply;

}

echo doSomething('Bob Tester', 12);
echo doSomething('Bob Tester');
echo doSomething('', 12);

, heredoc. , .

class Test {

  function Compare($a = '', $b = '') {

    if ($a == $b) 
      return $a;

    else
      return 'Guest';

  }

};

function doSomething($username = '') {

  $Test = new Test;

  $unme = 'Bob Tester';

  $reply = <<<EOT
  <h2>Example usage:</h2>
  Welcome {$Test->Compare($username, '')}<br />
  <br />
  Or<br />
  <br />
  Welcome {$Test->Compare($username, $unme)}

EOT;

  return $reply;

}

echo doSomething('Bob Tester');
0
source

Source: https://habr.com/ru/post/1771241/


All Articles