Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can improper indentation break php code?

Tags:

php

I am learning php from the user manual. Right now I am looking at the following code:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Untitled Document</title>
    </head>

    <body>
<?php
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>
    </body>
</html>

As is this code runs as expected and outputs: My name is "MyName". I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A

When I try to indent the php so that it is in front of the body tags the HTML beneath it gets commented out the chrome broswer shows an error:

Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\xampp\phpnotes\index.php on line 39

like image 830
oladitan Avatar asked Apr 11 '26 23:04

oladitan


1 Answers

Generally, no. Indenting PHP code will not affect it at all. However, there is an exception to this rule for heredoc. From the docs:

Warning

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

In short, your EOD; and EOT; lines must be on their own, with no tabs, spaces or anything else.

like image 172
rjdown Avatar answered Apr 13 '26 13:04

rjdown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!