¿Puedo usar un signo de almohadilla (#) para comentar en PHP?

6 minutos de lectura

avatar de usuario
Hubro

Nunca, nunca, he visto un archivo PHP usando hashes (#) por comentar. ¡Pero hoy me di cuenta de que realmente puedo! Supongo que hay una razón por la que todo el mundo usa // en cambio, así que aquí estoy.

¿Hay alguna razón, aparte de la preferencia personal, para usar // más bien que # ¿para comentarios?

  • Eso es un hash (o una libra o un cuadrado, según el país en el que se encuentre), no una etiqueta hash. Un hashtag es un medio para categorizar contenido en Twitter.

    – Quintín

    1 de febrero de 2012 a las 9:43

  • Podría usar el equivalente de escape HTML # si necesita el símbolo # en su código

    – dotoree

    1 de febrero de 2012 a las 9:53


  • pensé que el # el símbolo se llamaba hash tag… 🙁 No hay motivo para votar negativamente con tanta fuerza. Lección aprendida

    – Hubro

    1 de febrero de 2012 a las 10:35

  • me gusta usar # para comentarios de una sola línea, // por comentar el código & /* ... */ para bloques de comentarios

    – Juan Magnolia

    15 de noviembre de 2013 a las 18:56

  • Posible duplicado de PHP Comentarios # vs //

    – nawfal

    18 de octubre de 2015 a las 1:51

avatar de usuario
aziz

ACTUALIZACIÓN 2021: A partir de PHP 8, los dos personajes no son iguales. La secuencia #[ is used for Attributes.(Thanks to i336 for the comment)

Original Answer:

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.

  • Note that N++ (6.55) can’t always fold # comments correctly. I noticed that in large PHP files: 2k lines or more. Sometimes it starts to fold code on multiple #.

    – CoR

    Apr 14, 2014 at 13:47

  • I much prefer # comments over // ones .. but I’ve always been wondering if # is PSR complient .. Is it ?

    – Stphane

    Aug 11, 2015 at 7:36


  • Hash is helpful when describing routes, eg. # /news (code here) instead of // /news (code here). As for 2k LoC files, I think there are other problems than which comment tag to use 🙂

    – Juha Untinen

    Apr 1, 2016 at 6:48


  • AS OF PHP 8 THIS IS NO LONGER THE CASE: # will always be a comment operator, but the sequence #[ now marks the start of an “attribute” or annotation. (Which are pretty cool.) It’s a very small change (and can be worked around by adding a space, like # [), but means # can no longer be treated as “ignore everything to end of line.” So maybe don’t use # in autogenerated code.

    – i336_

    Jan 1, 2021 at 12:27


  • Thank you, @i336_. I’ve updated the answer to reflect this update.

    – Aziz

    Jan 1, 2021 at 16:33

PHP’s documentation describes the different possibilities of comments. See http://www.php.net/manual/en/language.basic-syntax.comments.php

But it does not say anything about differences between “//” and “#”. So there should not be a technical difference. PHP uses C syntax, so I think that is the reason why most of the programmers are using the C-style comments ‘//’.

  • Or it uses perl syntax, in which case “#” makes its appearance. And perl gets its comment syntax from the unix-ey shells.

    – Gerard ONeill

    Jun 17, 2019 at 12:41

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

RTM

  • // is a C style comment

    – user2607743

    Apr 12, 2020 at 0:27

user avatar
Sithu

Is there any reason, aside from personal preference, to use // rather than # for comments?

I think it is just a personal preference only. There is no difference between // and #. I personally use # for one-line comment, // for commenting out code and /** */ for block comment.

<?php
    # This is a one-line comment
    echo 'This is a test';

    // echo 'This is yet another test'; // commenting code

    /** 
     * This is a block comment
     * with multi-lines 
     */
    echo 'One final test';
?>

user avatar
Brandin

One might think that the # form of commenting is primarily intended to make a shell script using the familiar “shebang” (#!) notation. In the following script, PHP should ignore the first line because it is also a comment. Example:

#!/usr/bin/php
<?php

echo "Hello PHP\n";

If you store it in an executable file you can then run it from a terminal like this

./hello

The output is

Hello PHP

However, this reasoning is incorrect, as the following counterexample shows:

#!/usr/bin/php
#A
<?php

#B
echo "Hello PHP\n";

The first line (the shebang line) is specially ignored by the interpreter. The comment line before the PHP tag is echoed to standard output because it is not inside a PHP tag. The comment after the opening PHP tag is interpreted as PHP code but it is ignored because it is a comment.

The output of the revised version is

#A
Hello PHP

  • Actually, the shebang is outside the PHP code, so it is absolutely not a comment for PHP. Try removing the !, and run the file through php command line: it will print “#/usr/bin/php”. The reason why the shebang is ignored is because PHP recognize shebang lines at the very begining of files and ignore them.

    – Ninj

    Feb 18, 2015 at 17:24


  • Using php7.4, both comments are echoed. So the sheband is not (or no longer) ignored at all.

    – Chargnn

    Jan 15, 2020 at 21:25


  • @Chargnn, just tested it, it works in PHP 7.4 as well. It shouldn’t depend on the PHP version, this comment means nothing to PHP, only to the shell. Shell sees this comment, reads it, then removes it and passes the rest to PHP. Maybe you weren’t running it in a unix shell or some weird shell that doesn’t support this?

    – egst

    Feb 25, 2021 at 13:47

If you establish some rule sets in your team / project… the 2 types of comments can be used to outline the purpose of the commented code.

For example I like to use # to mute / disable config settings, sub functions and in general a piece of code that is useful or important, but is just currently disabled.

  • Actually, the shebang is outside the PHP code, so it is absolutely not a comment for PHP. Try removing the !, and run the file through php command line: it will print “#/usr/bin/php”. The reason why the shebang is ignored is because PHP recognize shebang lines at the very begining of files and ignore them.

    – Ninj

    Feb 18, 2015 at 17:24


  • Using php7.4, both comments are echoed. So the sheband is not (or no longer) ignored at all.

    – Chargnn

    Jan 15, 2020 at 21:25


  • @Chargnn, just tested it, it works in PHP 7.4 as well. It shouldn’t depend on the PHP version, this comment means nothing to PHP, only to the shell. Shell sees this comment, reads it, then removes it and passes the rest to PHP. Maybe you weren’t running it in a unix shell or some weird shell that doesn’t support this?

    – egst

    Feb 25, 2021 at 13:47

user avatar
Community

There’s no official PSR for that.

However, in all PSR example code, they use // for inline comments.

There’s an PSR-2 extension proposal that aims to standardize it, but it’s not official: https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions.md#commenting-code

// is more commonly used in the PHP culture, but it’s fine to use # too. I personally like it, for being shorter and saving bytes. It’s personal taste and biased, there’s no right answer for it, until, of course, it becomes a standard, which is something we should try to follow as much as possible.

  • The problem with standards in the Computer Science realm is that to make a standard, you have to have the best option, and in Computer Science there is no such thing as the best option. There are only wrong options, and better options. But “best option” does not exist.

    – user2607743

    Apr 12, 2020 at 0:43

¿Ha sido útil esta solución?

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Configurar y más información
Privacidad