PHP 可以用井號(#, number sign)註解?

可能是以前學校都教 C/C++,在自學 PHP 和 Laravel 的過程中一直都是使用 C-like 的註解方式。常見的就是以下幾種寫法:

// 單行註解

結果今天在公司的 code 發現了 # 開頭的程式?!

趕快上網查了一下,在 Stack Overflow 看到了 Can I use hash sign (#) for commenting in PHP? 這篇。回答者 Aziz 提到:

The answer to the question Is there any difference between using “#” and “//” for single-line comments in PHP? is no.

There is no difference. By looking at the parsing part of PHP source code, both “#” and “//” are handled by the same code and therefore have the exact same behavior.

從附上的 PHP 原始碼看來,# 和 // 的功用是一樣的了。來查查看官方文件是怎麼說:

PHP supports ‘C’, ‘C++’ and Unix shell-style (Perl style) comments. For example:

   echo 'This is a test'; // This is a one-line c++ style comment
   /* This is a multi line comment
      yet another line of comment */
   echo 'This is yet another test';
   echo 'One Final Test'; # This is a one-line shell-style comment

PHP 支援 C、C++ 和 Unix Shell 風格(Perl 風格)的註解。


# 單行註解