Can you put PHP inside PHP with echo? [closed]

In a situation where little snippets of PHP are used in the html a lot, like Wordpress, can you use PHP inside PHP echos?

Example:

<?php 
    echo "<?php the_author_meta('description'); ?>";
?>

As unnecessary as that may be, can it even be done? If not, one aspect of PHP that still seems to confuse me slightly is how to end and restart PHP when outputting HTML.

Case in point, Chris' answer here: How can I echo HTML in PHP? - I want so badly to put a ?> at the end of his example, but that causes errors. Can someone point me in the direction of some comprehensive info of how this starting/stopping with PHP works when blending with HTML, HTML that itself may use PHP snippets in it.


Solution 1:

Try:

<?php
    echo htmlspecialchars("<?php the_author_meta('description'); ?>");
?>

Solution 2:

You cannot have PHP echo more PHP code to be evaluated because PHP interprets your code in a single pass. If you have, say, <?php echo '<?php echo "hello"; ?>'; ?>, You will literally get the text, <?php echo "hello"; ?> as output, and the interpreter will not touch it.

You can, however, jump in and out of PHP at will:

<?php
echo "I am going to be interpreted by PHP.";
?>
I am not interpreted by PHP.
<?php
echo "But I am again.";
?>

If you think that you need to output PHP code that is itself re-evaluated, there is always a better way to accomplish this. If you give a specific example of what you are trying to accomplish (real-world case), then the folks here on SO would be happy to help.

Solution 3:

In regards to: "one aspect of PHP that still seems to confuse me slightly is how to end and restart PHP when outputting HTML."

<?php
// Do some wicked cool stuff in PHP here.
?>
<html>
<body>
Output some html here
<?php
//More awesome PHP stuff here.
?>
Back to html
</body>
</html>
<?php
// You can do any final stuff you want to do here.
?>

Or maybe you mean something more like this:

<table>
<?php 
foreach($person as $p){
  echo "<tr>";
  echo "<td>".$p['name']."</td>";
  echo "</tr>";
}
?>
</table>

Solution 4:

Yes, but it's a horrible idea. In this case, you should just write the function. If you want to "link" the multiple occurrences together, create your own function that does this (such as function describe() {the_author_meta('description');})

In general, you need to realise that anything between <?php and the next ?> will be considered a PHP block and parsed by the engine. Anything on in those blocks is left as is. If you're having specific issues, please ask about them specifically ;)