Use Heredoc or just output HTML?

I have PHP file like …

<?php 
	require_once('Header.php');
	Header::displayHeader();
?>
  <body>
  	Hello world.
  </body>
</html>

where my class is …


<?php
class Header {

	public static function displayHeader() {
?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
  </head>
<?php
	}
}
?>

Is that acceptable? Or should I use a Heredoc like this …


<?php
class Header {

	public static function displayHeader() {
	
		$header = <<<EOT
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
  </head>
EOT;
		echo $header;		
		
	}
}
?>

I like the former because the syntax highlighter of my editor works better with that. But wondering if it is bad practice, or whether it is common to do so.

Both are ok.

Agreed that both are OK, whatever is best to quickly glance at the script and see what it is supposed to do:

Try this:


<?php
$headerHeredoc = <<<EOT
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
  </head>
EOT;

class Header {

    public static function displayHeader()
  {
    echo $headerHeredoc;
  }
}
?> 

1 Like

IMHO Heredoc syntax comes in handy when the HTML has a lot of PHP in it. It makes the code a lot less messy. eg.

<!doctype html>
<html lang="<?php echo $lang; ?>">
  <head>
    <meta charset="<?php echo $charset; ?>">
    <meta http-equiv="X-UA-Compatible" content="<?php echo $x_ua_compat; ?>">
    <title></title>
  </head>

vs.

 $header = <<<EOT
<!doctype html>
<html lang="$lang">
  <head>
    <meta charset="$charset">
    <meta http-equiv="X-UA-Compatible" content="$x_ua_compat">
    <title></title>
  </head>
EOT;
        echo $header;

Though, consider this alternative “template inheritance” style.

<?php $title = 'My Web Page' ?>

<?php ob_start() ?>
    <h1>Hello</h1>
    <p>Hello, World!</p>
<?php $content = ob_get_clean() ?>

<?php require 'layout.php' ?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo $title ?></title>
  </head>
  <body>
      <?php echo $content ?>
  </body>
</html>

In my opinion if you’re running into these types of issues than there isn’t enough separation between the display and application logic. You should consider using some type of template layer to force separation between the two.Unbox any well known MVC framework and rarely are there ANY hard-coded, embedded HTML strings anywhere besides in the display/template layer. The example Jeff Mott provided is a very basic example of the traditional pattern you should probably be using.