Как закомментировать php в html
Перейти к содержимому

Как закомментировать php в html

  • автор:

Comment out HTML and PHP together

the page fails — it seems the PHP code is not being commented out. Is there a way to do this?

Peter Mortensen's user avatar

Matt Elhotiby's user avatar

7 Answers 7

Instead of using HTML comments (which have no effect on PHP code — which will still be executed), you should use PHP comments:

With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.

Just one note: you cannot nest C-style comments. which means the comment will end at the first */ encountered.

Как закомментировать php в html

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

The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // . ?> or # . ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that.

'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style comments. It is easy to make this mistake if you are trying to comment out a large block of code.

User Contributed Notes 12 notes

Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it’s easy for the next person to read. So something like this might help.

/* Title Here Notice the First Letters are Capitalized */

# Option 1
# Option 2
# Option 3

/*
* This is a detailed explanation
* of something that should require
* several paragraphs of information.
*/

// This is a single line quote.
?>

A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
<?php
//*
if ( $foo ) <
echo $bar ;
>
// */
sort ( $morecode );
?>

Now by taking out one / on the first line..

<?php
/*
if ($foo) <
echo $bar;
>
// */
sort ( $morecode );
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even «flip» two blocks, like this:
<?php
//*
if ( $foo ) <
echo $bar ;
>
/*/
if ($bar) <
echo $foo;
>
// */
?>
vs
<?php
/*
if ($foo) <
echo $bar;
>
/*/
if ( $bar ) <
echo $foo ;
>
// */
?>

It is worth mentioning that, HTML comments have no meaning in PHP parser. So,

WILL execute some_function() and echo result inside HTML comment.

As of php 8, single line comments starting exactly with «#[» have a special meaning: they are treated as «attributes», and they must respect the expected syntax. See: https://www.php.net/manual/en/language.attributes.php

So the following code throws an error in php 8+, while it is perfectly valid in php <8:
<?php
#[

my super cool comment

]
?>

To be safe, just always use «//» comments instead of «#». Maybe in the future there will be other special meanings for the «#» comments, who knows.

Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
<?php
/**
* The second * here opens the DocBook commentblock, which could later on<br>
* in your development cycle save you a lot of time by preventing you having to rewrite<br>
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie <br> tags) to create something of a layout.

MSpreij (8-May-2005) says /* .. */ overrides //
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with:
// then /* and */ are «overridden» until after end-of-line
/* then // is «overridden» until after */

Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won’t hurt me 😉

Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment 😉

// Control
echo microtime (), «<br />» ; // 0.25163600 1292450508
echo microtime (), «<br />» ; // 0.25186000 1292450508

// Test
echo microtime (), «<br />» ; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime (), «<br />» ; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).

it’s perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as <?php echo ‘something’ ; //comment ?>

<?php
if( 1 == 1 )
<
// ?>
>
?>

i discovered this «anomally» when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match(‘/^(?>c|b)at$/’, ‘cat’, $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don’t know about # style comments, i don’t ever personally use them.

a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli’s comment from nov’05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in: just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out. but hey, to each their own 🙂

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include 🙂

for example, placed at top of file:

<?php $ver3 = TRUE ;
$debug2 = FALSE ;
?>

and then deeper inside the file:

<?php if ( $ver3 ) <
print( «This code is included since we are testing version 3» );
>
?>

<?php if ( $debug2 ) <
print( «This code is ‘commented’ out» );
>
?>

In php there are 3 types of comments
1.single line c++ style comment(//)
2.single line Unix shell stype comment(#)
3.multi line c style comment(/*/)

single or multi line comment comes to the end of the line or come first to the current block of php code.

HTML code will be printed after //. > or #. >
closing tag breaks the php mode and return to html mode.

different comments in different tags:
===================================
<H1>Standard tag: <?php //echo » standard tag»; ?> single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Standard tag:single line c++ style comment'</p>

<H1>Standard tag: <?php # echo » standard tag»; ?> single line unix shell style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Standard tag:single line unix shell style comment'</p>

<H1>Standard tag: <?php /*echo » standard tag»; */ ?> multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Standard tag:multi line c style comment'</p>

<H1>short echo tag: <?= // » short echo tag»; ?> single line c++ style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

<H1>short echo tag: <?= # » short echo tag»; ?> single line c++ style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

<H1>short echo tag: <?= /*echo » short echo tag»*/ ; ?> multiple line c style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

<H1>Short tag: <? //echo » short tag»;?>single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Short tag:single line c++ style comment'</p>

<H1>Short tag: <? #echo » short tag»;?>single line unix shell style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Short tag:single line unix shell style comment'</p>

<H1>Short tag: <? /* echo » short tag»;*/?>multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Short tag:multi line c style comment'</p>

<H1>Script tag: <script language=»php»> // echo » script tag»;</script>single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Script tag:single line c++ style comment'</p>

<H1>Script tag: <script language=»php»> /* echo » script tag»;*/</script>multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show ‘Script tag:multi line c style comment'</p>

<H1>Script tag: <script language=»php»> # echo » script tag»;</script>single line unix shell style comment</H1>
<p>The header above will not break php mode </p>

Как закомментировать на время код HTML, CSS или PHP, JS

как закомментировать код

…сегодня мы в этой коротенькой, но полезной статье, разберемся, как же комментируется различный программный код. Много говорить не стану, ибо если вас подобное заинтересовало, то вы уже столкнулись с вопросами этой задачи, и представление о ней имеете.

(в финале статьи подробное видео о правилах и способах комментирования кодов)

  • ошибки в комментариях к коду — по версиям php
  • php 8
  • Комментируем код CSS
  • Комментируем код HTML
  • как закомментировать JavaScript
  • Комментируем код PHP

Вы зашли по адресу… но несколько слов для ясности и пользы дела. Наверняка видели, как это делается с CSS-кодом , так как сss представляет наибольший интерес у многих начинающих, как и я.

Но обратите внимание, что комментарии используются также и в html и php… А ведь большинство начинающих путаются на начальном этапе своей работе с сайтом и не знают, как дописать себе необходимые пояснения. Ведь бывает же так, например, вам потребуется на какое-то время деактивировать код html, а потом снова возобновить его функцию — это запросто реализовать, если вы сделали себе пометки на «полях», да мало ли что.

Но что следует помнить о «комментариях» вообще — тут всё в строгой зависимости от того, с каким файлом вы работаете конкретно, а следовательно и код применения различен.

ошибки в комментариях к коду — по версиям php

php 8

время от времени языки программирования меняются (их версии), а следовательно относитесь внимательнее к тому, что и как комментируете!

Как известно, не так давно вышла версия php 8 — некоторые пользователи столкнулись с проблемами!

В данной статье коснемся, скажем так, синтаксиса — правописания))…

Например, если комментируете в самом финале кода, то обязательно соответственно закрывайте комментарий! иначе, в новейших версиях php (подобные правила касаются многих ЯПов) бесконечно закомментированный блок вызовет ошибки! Белый экран.

закомментировать код

…далее: никогда не ЛЕПИТЕ друг к дружке символы комментариев к тегам кода. неряшество в коде, как и в жизни, вызывает неприличные ошибки.

На мой взгляд, лучше потратить несколько лишних минут времени, но написать чистенький и аккуратный код и комментарии. Это в будущем сэкономит массу времени!

Как закомментировать код в HTML, PHP, JavaScript, CSS?

Итак, что значит закомментировать код, и для чего эта возможность была придумана?
Закомментировать код – значит написать комментарии в коде. Закомментировать код – значит оставить текст-шпаргалку для разработчиков веб-сайтов, чтобы помочь им быстрее сориентироваться в коде. Комментарий в коде пользователю невидим.

Как закомментировать код в HTML, PHP, JavaScript, CSS?

Внимание: комментарии в коде для каждого языка программирования прописываются по-разному. Если не придерживаться конкретных правил, ваш код может не работать.

Чтобы вам сейчас все прояснилось, посмотрите примеры, как закомментировать код HTML, php, css, JavaScript и .htaccess.

Комментарии в коде HTML:

Пример с применением:

Комментарии в коде PHP:

В php вы можете использовать любой из трех видов комментариев, которые приведены ниже:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *