Это пример
Заголовок вверху выведет ‘Это пример’.
‘C’-комментарии заканчиваются при первой же обнаруженной последовательности */ . Убедитесь, что вы не вкладываете друг в друга ‘C’-комментарии. Очень легко допустить эту ошибку при комментировании большого блока кода.
/*
echo «Это тест»; /* Этот комментарий вызовет проблему */
*/
?>?php
User Contributed Notes 11 notes
9 years ago
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.
?>
18 years ago
A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
//*
if ( $foo ) echo $bar ;
>
// */
sort ( $morecode );
?>
Now by taking out one / on the first line..
/*
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:
//*
if ( $foo ) echo $bar ;
>
/*/
if ($bar) echo $foo;
>
// */
?>
vs
/*
if ($foo) echo $bar;
>
/*/
if ( $bar ) echo $foo ;
>
// */
?>
1 year ago
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 #[~~ 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.
10 years ago
It is worth mentioning that, HTML comments have no meaning in PHP parser. So,
WILL execute some_function() and echo result inside HTML comment.
18 years ago
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:
/**
* The second * here opens the DocBook commentblock, which could later on
* in your development cycle save you a lot of time by preventing you having to rewrite
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie
tags) to create something of a layout.
17 years ago
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 */
19 years ago
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 😉
16 years ago
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
if( 1 == 1 )
// ?>
>
?>
?php>
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.
13 years ago
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 (), «
» ; // 0.25163600 1292450508
echo microtime (), «
» ; // 0.25186000 1292450508
// Test
echo microtime (), «
» ; // 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 (), «
» ; // 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).
13 years ago
If you are using editor with code highlight, it’s much easier to notice error like /* */ */.
17 years ago
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:
and then deeper inside the file:
print( «This code is included since we are testing version 3» );
>
?>
print( «This code is ‘commented’ out» );
>
?>
- Основы синтаксиса
- Теги PHP
- Изолирование от HTML
- Разделение инструкций
- Комментарии
- Copyright © 2001-2024 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
ITExplain

Please read How to support Ukraine if you haven’t done it yet!
Advertisements
Recent Posts
- Error loading shared library libresolv.so.2: No such file or directory
- Windows Server – A service installation section in this INF is invalid
- How to clone git without/ignore lfs files
- ImportError: no module named ‘ssd1306’ in micropython
- Fuse mount in docker or docker-compose
Recent Comments
Archives
Categories
Meta
Как в PHP закомментировать строку
Spread the love

В PHP для того, чтобы закомментировать код необходимо использовать // или /* */ .
Пример кода:
А это комментарий на несколько строк
*/
echo “” ;
//print “Hello world. ” // Этот код не будет исполнятся
?>При исполнение приведенного кода получим результат:
Leave a Reply Cancel reply
You must be logged in to post a comment.
Proudly powered by WordPress. Theme: Flat 1.7.11 by Themeisle.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Manage consent
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie Duration Description cookielawinfo-checkbox-analytics 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Analytics». cookielawinfo-checkbox-functional 11 months The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category «Functional». cookielawinfo-checkbox-necessary 11 months This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category «Necessary». cookielawinfo-checkbox-others 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Other. cookielawinfo-checkbox-performance 11 months This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category «Performance». viewed_cookie_policy 11 months The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data. Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
Как закомментировать код на PHP ?
Во время написания скриптов на PHP периодически требуется для целей отладки или для указания комментария, отмечать некоторые строки как комментарии. В языке программирования PHP имеется 2 вида таких комментариев:
Однострочный комментарий в PHP.
Однострочный комментарий в PHP применяется:
- для быстрого заккомментирования одной-двух строчек кода;
- а также применяется для того, чтобы оставить небольшой комментарий к коду
Однострочный комментарий в PHP это два символа слеша // . В примере кода выше имеется 4 таких комментария.
Любой текст, код который находится за последовательностью символов // будет проигнорировано интерпретатором PHP и не будет обрабатываться.
В результате работы кода выше будет выведена, например такая строка:
Сегодня дата 2019-03-25
Многострочный комментарий
В случае, когда комментарием одной строкой не обойтись, то следует использовать многострочный комментарий. Его синтаксис следующий:
Любой текст или код, который будет заключен, между симовалами /* и */ воспринимается как комментарий и не будет обработан.
Гораздо чаще многострочный комментарий будет выглядеть, как:
/*
* Здесь некоторый текст
* Еще немного текста
* .
*/Также многострочный комментарий может быть записан в одну строку:
/* здесь некоторый комментарий */
Наиболее часто в профессиональной разработке на PHP вы будете встречать и использовать сами, многострочные комментарии в стиле PHPDoc (для чего такие комментарии используются, подробнее будет в отдельной статье):
Как можете обратить внимание, что в примере кода выше, такой специальный многострочный комментарий описывает тип входных аргументов (array), и тип возвращаемого значения (float или int) для функции getSum().
Будут ли видны Ваши комментарии в браузере?
Написанный вами PHP код выполняется только на сервере, и результат работы любого скрипта PHP этот текст, который уже отдается в браузер. В случае ВЕБ программирования результатом работы PHP скриптов, как правило является сгенерированыый HTML документ с тегами. И самое главное, что интерпретатор php, выполняя скрипт, игнорирует все строки заключенные в символы комментариев.
А значит ни одна строчка или строчки вашего кода, отмеченные как комментарии, никогда не будут обработаны, а их содержимое никогда не будет доступно в браузере у конечного пользователя.
Резюмируем.
При написании кода на языке программирования PHP принято использовать однострочные комментарии (//………) и многострочные комментарии (/* ………………… */).
Как закомментировать на время код HTML, CSS или PHP, JS

…сегодня мы в этой коротенькой, но полезной статье, разберемся, как же комментируется различный программный код. Много говорить не стану, ибо если вас подобное заинтересовало, то вы уже столкнулись с вопросами этой задачи, и представление о ней имеете. Также о представлении можно прочесть предыдущую статью Оформление внешних и внутренних ссылок визуальными иконками CSS (в финале статьи подробное видео о правилах и способах комментирования кодов)
- ошибки в комментариях к коду – по версиям php
- php 8
- Комментируем код CSS
- Комментируем код HTML
- как закомментировать JavaScript
- Комментируем код PHP
Вы зашли по адресу… но несколько слов для ясности и пользы дела. Наверняка видели, как это делается с CSS-кодом , так как сss представляет наибольший интерес у многих начинающих, как и я.
Но обратите внимание, что комментарии используются также и в html и php… А ведь большинство начинающих путаются на начальном этапе своей работе с сайтом и не знают, как дописать себе необходимые пояснения. Ведь бывает же так, например, вам потребуется на какое-то время деактивировать код html, а потом снова возобновить его функцию – это запросто реализовать, если вы сделали себе пометки на “полях”, да мало ли что.
Но что следует помнить о “комментариях” вообще – тут всё в строгой зависимости от того, с каким файлом вы работаете конкретно, а следовательно и код применения различен.