Skip to content

PHP 运算符

运算符是用于对值(操作数)执行操作的特殊符号。PHP 包含广泛的运算符,分类如下:

  • 算术运算符 (Arithmetic operators)
  • 赋值运算符 (Assignment operators)
  • 比较运算符 (Comparison operators)
  • 递增/递减运算符 (Increment/Decrement operators)
  • 逻辑运算符 (Logical operators)
  • 字符串运算符 (String operators)
  • 数组运算符 (Array operators)
  • 条件赋值运算符 (Conditional assignment operators)
  • 类型运算符 (Type operators)
  • 位运算符 (Bitwise operators) (在 Web 开发中不常用,此处不作介绍)
  • 错误控制运算符 (Error control operator)
  • 执行运算符 (Execution operator)

用于数字值执行常见的数学运算。

用于将值赋给变量。基本赋值运算符是 =. 组合运算符执行一个操作,然后将结果赋值。

用于比较两个值。这些运算符通常返回一个布尔值 (true 或 false)。

最佳实践:尽可能优先使用严格比较 (===, !==),以避免由于自动类型转换(类型杂耍/类型强制转换)造成的意外行为。

用于增加或减少变量的值,通常是加一或减一。

示例:

<?php
$a = 5;
echo ++$a; // Outputs 6 (a is now 6)
$b = 5;
echo $b++; // Outputs 5 (b is now 6)
echo $b; // Outputs 6
$c = 5;
echo --$c; // Outputs 4 (c is now 4)
$d = 5;
echo $d--; // Outputs 5 (d is now 4)
echo $d; // Outputs 4
?>

用于组合条件语句,通常操作布尔值。

注意:&& 和 || 具有短路行为。如果可以根据左侧操作数确定结果(例如,false && ... 或 true || ...),则不会对右侧操作数进行求值。

PHP 提供了两个专门用于字符串操作的运算符。

示例:

<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName; // "John Doe"
$message = "Hello";
$message .= ", world!"; // $message is now "Hello, world!"
echo $fullName . "\n";
echo $message . "\n";
?>

用于组合或比较数组。

注意:数组的 + 运算符通常不如 array_merge() 或 array_replace() 等函数直观,后者在处理重复键时提供了不同的行为。

这些运算符提供了基于条件(通常涉及对 null 的检查)赋值的简写方式。

示例:

<?php
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor'; // $status = 'Adult'
$username = $_GET['user'] ?: 'Guest'; // Uses 'Guest' if $_GET['user'] is empty or not set
$configValue = $settings['value'] ?? 100; // Uses 100 if $settings['value'] is null or not set
$options['timeout'] ??= 5000; // Sets $options['timeout'] to 5000 only if it wasn't already set
echo "Status: $status\n";
echo "Username: $username\n";
echo "Config Value: $configValue\n";
print_r($options);
?>

警告:强烈不推荐使用错误控制运算符 (@)。它会隐藏潜在问题,使调试变得异常困难。几乎总是最好显式地检查潜在错误(例如,使用 isset()、file_exists()、try...catch)或配置正确的错误报告机制。

警告:同样强烈不推荐使用反引号运算符,如果在命令中包含任何用户输入,则存在重大的安全风险。当需要与系统 shell 交互时,最好使用更安全的替代方案,如 shell_exec()、exec() 或 proc_open(),并进行适当的输入转义(例如,escapeshellarg()、escapeshellcmd())。