2014-11-22 56 views
2

我正在學習用戶手冊中的php。現在我在看下面的代碼:可以不正確的縮進打破php代碼?

<!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> 

正如該代碼運行正常和輸出:我的名字是「MYNAME」。我正在打印一些Foo。現在,我正在打印一些Bar2。這應打印一資「A」:一個

當我試圖縮進PHP,使其在身體前方標記下它被註釋掉鉻broswer的HTML顯示錯誤:

解析錯誤:語法錯誤,C:\ xampp \ htdocs \ xampp \ phpnotes \ index.php中的文件意外結束,第39行

回答

4

通常,縮進PHP代碼根本不會影響它。然而,這個規則對於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.

總之,你EOD;EOT;線必須靠自己,沒有製表符,空格或其他任何東西。

+2

++ 1用於識別引起這個問題的規則。如果只有OP只是閱讀他使用的語言功能的文檔... – 2014-11-22 18:17:03

+0

我從來沒有讀過一個正式的語言文檔,用於所有用於魯莽放棄的if語句。沒有時間RTFM的一切:) – STW 2014-11-22 18:21:28

+0

@STW:如果你寫一個'if'語句,它不起作用,那麼你應該絕對RTFM。沒有煩惱這麼做 - 特別是在浪費某人_else's_時間問這個問題 - 只是在進攻性的懶惰! – 2014-11-22 18:30:37

0

rjdown's answer是正確的

什麼,你可能要考慮的是儘量減少你的PHP和HTML的混合。通常,這是通過一種稱爲「模板化」的方法完成的,其中有兩個獨立的文件 - 一個幾乎完全是HTML,偶爾用PHP語句來回顯函數或變量值返回的字符串。另一個文件是純PHP,用於生成將顯示的值。通常,模板文件使用.phtml擴展名,而後備腳本使用.php

這裏是一個Hello World例子:

這裏的 「視圖模型」,viewmodel.php

<?php 

class ViewModel { 
    public function sayHello($name = null) { 
     if (is_null($name)) 
     { 
      $name = 'World'; 
     } 

     return sprintf('Hello %s', $name); 
    } 
} 

而這裏的 「視圖」,view.phtml

<?php 
    require_once('viewmodel.php'); 
    $model = new ViewModel(); 
?> 

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

    <body> 
     <?php echo $model->sayHello(); ?> 
    </body> 
</html> 

在那裏,您將加載view.phtml在您的瀏覽器來獲取輸出。

這種類型的方法並不是PHP所特有的,幾乎在任何系統中使用模板,而且在大多數情況下,一種語言的輸出必須在另一種語言中格式化。