PHP Syntax


PHP scripts are executed on the server, and then the pure HTML result is sent back to the browser.

PHP uses<?php ?>to wrap code.


Basic PHP Syntax

PHP scripts can be placed anywhere in a document.

PHP scripts start with<?phpand end with?>:

<?php
// PHP 代码
?>

The default file extension for PHP files is.php。

PHP files usually contain HTML tags and some PHP script code.

Examples

<?php
// PHP code is written between <?php and ?>
echo "Hello, PHP!";
?>
  • <?php ...?>is the standard PHP tag.
  • echo is used to output content.
  • Each statement must end with a;。

Below, we provide a simple PHP file example that outputs the text "Hello World!" to the browser:

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Every line of code in PHP must end with a semicolon. A semicolon is a delimiter used to separate sets of instructions.

In PHP, there are two basic instructions for outputting text in the browser:echoandprint。


Comments in PHP

In PHP, comments are used to explain what code does; they are not executed and are not output to the page.

There are mainly three forms of comments:

1. Single-line comments (2 ways)

Use//

<?php
// 这是单行注释
echo "Hello"; // 也可以放在语句后面
?>

Use#

<?php
# 这是另一种单行注释
echo "World";
?>

Features:

  • from//or#Starts at ... and continues to the end of the line.
  • Often used for brief descriptions.

2. Multi-line comments (block comments)

Use/* ... */</p>

<?php
/*
这是多行注释
可以写多行文字
不会被执行
*/
echo "PHP";
?>

Features:

  • with/*starts with ...*/ends with ...
  • Can be written across multiple lines.
  • Often used for longer code explanations, function comments, etc.

3. Documentation comments (DocBlock comments)

This is a special form of multi-line comment, used to generate API documentation, suitable for describing classes, functions, etc.

<?php
/**
 * 打印问候语
 *
 * @param string $name 用户名
 * @return string 返回问候语
 */
function sayHello($name) {
    return "Hello, $name!";
}
?>

Features:

  • use/** ... */Wrapped (note the two asterisks)
  • Supports @param, @return, @var, @author
  • Often used with IDEs or documentation generation tools (e.g., phpDocumentor)
Purpose Recommended comment form Example
Briefly explain a line of code //or# // Output information
Explain a block of code /* ... */ Comments for logical blocks
Function/class documentation /** ... */ DocBlock Used to describe parameters, return values, purpose, etc.

Examples

<!DOCTYPE html>
<html>
<body>

<?php
// This is a PHP single-line comment

/*
This is
PHP multi-line
comment
*/
?>


</body>
</html>

Run Example »
Other Extensions