PHP: return and the HEREDOC syntax

PHP just threw up this error, which had me stumped for a while:

PHP Parse error:  syntax error, unexpected end of file, expecting variable (T_VARIABLE) or heredoc end (T_END_HEREDOC) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in /path/to/file/test.php on line 17

You’ll get this exception if you try to immediately return a heredoc declaration.

function hello(){
  return <<< END
    World
  END;
}

If you assign it to a variable and try and return that, you’ll get a slightly different error.

function hello(){
  $val = <<< END
    World
  END;

  return $val;
}

echo hello();

Produces the error:

PHP Parse error:  syntax error, unexpected end of file in /path/to/file/test.php

In both cases, the issue is that the END; statement of the heredoc declaration is indented. A closing heredoc statement must start in column 0, like so:

function hello(){
  return <<< END
    World
END;
}

Once you remove your indentation from that line, things should work as expected

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply