简体   繁体   中英

Use of increment operator in heredoc

I want to increase the value of a variable by using the increment operator in heredoc. My current code is given below...

$counter = 0;
for($i = 0; $i<10; $i++):
echo <<< EOT
    $counter++ <br/>
EOT;
endfor;

Its output is...

0++
0++
.
.

Mean post-increment operator is not working.

I have also tried pre-increment, like given below...

echo <<< EOT
   ++$counter <br/>
EOT;

Its output is...

++0
++0
.
.

Mean pre-increment operator is also not working.

I have also tried to put increment operation inside curly braces, like given below...

echo <<< EOT
    {++$counter} <br/>
EOT;

But again no luck. Output is....

{++0} 
{++0} 
.
.

I have also searched it on google but didn't find anything useful.

I know if I can increase value before heredoc then I can print it in here doc correctly

$counter = 0;
for($i = 0; $i<10; $i++):
++$counter;
echo <<< EOT
    $counter <br/>
EOT;
endfor;

It works fine.

But I want to use increment operator in heredoc, just like we use in case of single or double quoted with echo .

But it seems like heredoc doesn't support increment operation.

The complex/curly variable syntax {$var…} does only allow variable access expressions, but not PHP expressions per se.

  • For example {$var[…]}
  • Or {$var(…)}
  • And {$var->prop…}
  • And {${stat::$lookup}}

There can't be arithmetic operators within the { + } itself. But only between […] or (…) used alongside.

*

One common workaround is to utilize variable function names:

$func = "htmlspecialchars";  // or any other no-op function
echo <<<HEREDOC
    counter = {$func($counter++)}
HEREDOC;

Where you can easily use full expressions in the curly var syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM