PHP 语法

`<?php ?>` 标记、语句、注释、以及和 HTML 混排。

Beginner
Key PointsPHP 代码必须包在 `<?php ... ?>` 里;只有一段纯 PHP 文件可以省略结束标记。

标记

PHP
<?php
// 标准标记,永远可用
echo "标准标记\n";
?>

<?= "短 echo 标记,等价于 echo" ?>

<?php
// 纯 PHP 文件建议省略 ?>,避免意外输出空白字符
echo "结束\n";
Output
标准标记
短 echo 标记,等价于 echo
结束
**Omit ?>** in pure PHP files. Whitespace after the closing tag gets output and breaks header() with headers already sent — a bug that costs real time to find.

语句与注释

PHP
<?php
// 单行注释
# 也是单行注释(少用)
/* 多行注释 */
/** 文档注释,IDE 和 phpDocumentor 会读 */

$a = 1;
$b = 2;
echo $a + $b, "\n";      // echo 可以接多个参数

/**
 * 计算两数之和
 * @param int $x
 * @param int $y
 * @return int
 */
function add(int $x, int $y): int
{
    return $x + $y;
}

echo add(1, 2), "\n";
Output
3
3

和 HTML 混排

PHP
<?php $items = ['苹果', '香蕉', '橙子']; ?>
<ul>
<?php foreach ($items as $item): ?>
  <li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>
Output
<ul>
  <li>苹果</li>
  <li>香蕉</li>
  <li>橙子</li>
</ul>

Alternative syntax like foreach (...): ... endforeach; exists for templates: it reads better than braces when mixed with HTML tags.

变量与命名

PHP
<?php
$name = "张三";           // 变量以 $ 开头
$userName = "李四";       // 驼峰
$user_name = "王五";      // 下划线(WordPress 风格)
$_private = "内部";       // 下划线开头
$中文变量 = "可以用";      // 技术上可以,但不建议

echo $name, $userName, $user_name, $_private, $中文变量, "\n";
Output
张三李四王五内部可以用

Variable names are case-sensitive ($name and $Name differ) but function and class names are not. A historical inconsistency — just pick one naming style and stay with it.

常见错误

PHP
<?php
// 忘记分号
// echo "a"
// echo "b";

// 使用未定义变量:警告,值为 null
echo $undefined ?? "未定义", "\n";

// 数组越界:警告
$arr = [1, 2];
echo $arr[5] ?? "越界", "\n";
Output
未定义
越界

Friends & Partners