PHP: return and the HEREDOC syntax

10 Jan 2014 in TIL

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.

php
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.

php
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:

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

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