Declaring a string in PHP with a Heredoc/Nowdoc block

Published on 2022-04-30 • Modified on 2022-04-30

This snippet shows how to declare a string in PHP with a Heredoc and Nowdoc block. This one is for me as I always forget how to do! As you can notice, the synthax highlighter is lost in the second block with the single quotes to dellare the Nowblock. With this block type, all the raw string is kept and variables are not replaced. It also works with constants and class properties.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet200Trait
{
    public function snippet200(): void
    {
        $name = 'COil';

        $heredoc = <<<HEREDOC
Heredoc example
on multiple lines
my name is $name


HEREDOC;

        echo $heredoc;

        $nowdoc = <<<'NOWDOC'
Nowdoc example
on multiple lines
my name is $name <- the name variabled isn't replaced here !
"<<'/\'>>"

NOWDOC;

        echo $nowdoc;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet