Quantcast
Channel: Fixes – mheap
Viewing all articles
Browse latest Browse all 35

PHP: return and the HEREDOC syntax

$
0
0

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


Viewing all articles
Browse latest Browse all 35

Trending Articles