The Perils of Nested Multiline Comments in PHP
Jul 26, 2025 am 09:53 AMPHP does not support nested multiline comments, and attempting to nest them can cause unexpected code execution or parse errors; the first / closes the entire comment block, so any code following it—even if intended to be commented—will be executed, leading to bugs or fatal errors when functions are inadvertently redeclared; to avoid this, use // comments, IDE block commenting, or wrap code in if (0) { } instead of / */ when commenting out code containing existing comments.
You can't nest multiline comments in PHP — and trying to do so can lead to subtle, hard-to-catch bugs. While this might seem like a minor language quirk, it's a real pitfall, especially when commenting out large blocks of code during debugging or refactoring.

PHP only recognizes /* */
as multiline comment delimiters, and the first */
closes the entire comment block — regardless of how many /*
came before it. This means nesting doesn’t work the way you might expect from other languages or programming constructs.
What Happens When You Try to Nest?
Consider this seemingly harmless code:

/* Some important function /* This is a nested comment */ Still inside what I thought was a comment */ echo "Hello, world!";
You might expect the entire block to be commented out — including the echo
statement. But here's what actually happens:
- The first
/*
starts the comment. - The first
*/
(after "nested comment") ends the comment. - Everything after that — including
Still inside...
and theecho
— is executed as PHP code.
So your "commented-out" echo
will run, and you’ll get output. Worse, if there’s invalid or incomplete PHP syntax after the premature */
, you’ll get a parse error that’s confusing to debug.

Why This Is Dangerous in Practice
The biggest risk isn't theoretical — it's when developers use /* ... */
to temporarily disable chunks of code.
Imagine this scenario during debugging:
/* function processUserData($data) { /* Validate input */ if (!isValid($data)) { logError("Invalid data"); return false; } performAction($data); } */
Looks safe, right? But the inner comment (/* Validate input */
) contains a */
, which terminates the outer comment early. The result?
function processUserData(...)
is no longer commented out.- If this file is included or run, the function gets defined — possibly causing conflicts or unintended behavior.
- Even worse: if the function already exists, you’ll get a fatal "Cannot redeclare" error.
This kind of mistake is especially dangerous because:
- There’s no warning from PHP.
- Syntax highlighters sometimes fail to catch it, coloring everything as "commented" when it’s not.
- The error may appear far from the actual cause.
Safer Alternatives
Instead of relying on /* */
, use these safer approaches:
Use multiple line comments (
//
)
Especially for temporary debugging:// function processUserData($data) { // if (!isValid($data)) { // logError("Invalid data"); // return false; // } // performAction($data); // }
Use IDE block commenting
Most editors let you select code and toggle//
on each line with a shortcut. It’s fast and safe.Use
#
for shell-style comments
Same behavior as//
, but some prefer it for visual distinction.For large blocks, consider wrapping in
if (0) { ... }
Example:if (0) { function processUserData($data) { /* Validate input */ if (!isValid($data)) { logError("Invalid data"); return false; } performAction($data); } }
This ensures the code is parsed (so syntax errors are still caught) but never executed.
Bottom Line
PHP’s multiline comments don’t support nesting — full stop. Relying on them to comment out code with existing
/* */
comments inside is asking for trouble. The parser doesn’t care about indentation or intent; it stops at the first*/
.The fix? Avoid
/* */
for commenting out code during development. Stick to//
or use conditional blocks. It’s a small habit change that prevents big headaches.Basically: if you're commenting out code that contains any
/*
or*/
, assume it will break. Plan accordingly.The above is the detailed content of The Perils of Nested Multiline Comments in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Single-line comments (//) are suitable for short, local instructions or debugging, 1. Use // for in-line comments or temporarily disable code; 2. Use // for multi-line comments to provide detailed descriptions of complex logic or comment large pieces of code; 3. Use /*/ to write PHPDoc to implement structured documents and integrate with the IDE; 4. Avoid comments to be obvious code; 5. Always keep comments updated to ensure comments clearly convey intentions rather than just describe operations, thereby improving code maintainability.

PHPdoesnotsupportnestedmultilinecomments,andattemptingtonestthemcancauseunexpectedcodeexecutionorparseerrors;thefirst/closestheentirecommentblock,soanycodefollowingit—evenifintendedtobecommented—willbeexecuted,leadingtobugsorfatalerrorswhenfunctionsa

Awell-structuredfileheaderimprovescodereadabilityandcollaborationbyprovidingkeyfileinformationupfront.1.Includethefile’spurpose,author,creationandmodificationdates,version,license,dependencies,andoptionalnotes.2.Useaconsistentmultilinecommentformatli

PHPDoccommentsprovidetypehints,enableautocomplete,detecterrors,andsupportnavigationinIDEsbyactingasstructuredmetadata.2.Specialinlinecommentslike//TODOor//FIXMEareparsedintoactionabletasks,allowingdeveloperstonavigate,filter,andtrackworkdirectlyfromt

PHPDocsignificantlyenhancesPHPcodemaintainabilityandclarity.1.Itprovidestypeclarityevenwithoutstricttyping,documentingparameters,returnvalues,andpropertieswithprecision.2.Itdescribescomplexreturntypeslikestructuredarrays,nullablevalues,anduniontypes,

PHPblockcommentingisessentialfordocumentinglogic,disablingcode,andcreatingstructureddocblocks;1.Use//formulti-linecommentsbutavoidnesting,asitcausesparseerrors;2.Youcansafelyinclude//commentsinside//blocks;3.Alwayscloseblockcommentswith/topreventunin

PHPDoccommentsarenotjustfordocumentation—theyserveasstructuredmetadatathatenhancecodereliabilityandmaintainability.1)TheyprovidetypehintsbeyondPHP’snativesyntax,allowingprecisedefinitionslikearrayornullabletypes,whichtoolslikePHPStanuseforstaticanaly

PHP's Heredoc and Nowdoc are effective tools to improve code readability and maintainability. 1. Heredoc supports variable interpolation, suitable for dynamic content such as HTML or JSON; 2. Nowdoc does not parse variables, suitable for plain text output; 3. Both avoid the confusion of quotation escapes and string splicing, making multi-line strings clearer; 4. When using it, make sure that the end identifier occupies one line and has no front and back spaces; 5. Direct insertion of untrusted data should be avoided to prevent security risks; 6. Code readability can be enhanced through unified naming separators (such as HTML, SQL). Reasonable use can significantly reduce cognitive load and improve development efficiency.
