PHP 备忘清单(速查表)详解:从基础语法到 PHP 8 新特性
2026/9/23 12:41:16 网站建设 项目流程
  • 文档
  • 知识库
  • 教程
  • 开发工具

【免费下载链接】reference

为开发人员分享快速参考备忘清单(速查表)

项目地址:https://gitcode.com/jaywcjlove/reference
点击查看免费下载

本篇指南以 docs/php.md 为骨架,系统梳理 PHP 的核心语法体系:变量与类型、字符串与数组操作、运算符、条件与循环、函数与类的高级写法,以及异常处理、Nullsafe 运算符等 PHP 7.4 / 8.0 新特性。读完本文,你将拥有一份可快速查阅、可直接复制运行的 PHP 实战速查手册,并能在项目开发中熟练运用 match 表达式、箭头函数、可空返回类型等现代 PHP 能力。

入门

hello.php

PHP 代码以<?php开放标签开头,echoprint都可用于输出内容,区别在于echo没有返回值且支持逗号分隔多参数,print始终返回 1:

<?php // 以 PHP 开放标签开头 echo "Hello World\n"; print("Hello jaywcjlove.github.io"); ?>

将上述内容保存为hello.php后,在终端运行:

$ php hello.php

变量 Variables

PHP 变量以$符号开头,无需显式声明类型即可赋值;unset()用于删除变量,释放其引用:

$boolean1 = true; $boolean2 = True; $int = 12; $float = 3.1415926; unset($float); // 删除变量 $str1 = "How are you?"; $str2 = 'Fine, thanks';

变量名区分大小写,布尔值与关键字不区分大小写。查看: Types

字符串 Strings

双引号字符串会解析其中的变量(插值),单引号字符串不会;.是字符串连接运算符,.=是连接赋值运算符:

$url = "jaywcjlove.github.io"; echo "I'm learning PHP at $url"; // 连接字符串 echo "I'm learning PHP at " . $url; $hello = "Hello, "; $hello .= "World!"; echo $hello; # => Hello, World!

查看: Strings

数组 Arrays

PHP 数组本质是有序映射表(Map),[]array()两种语法等价;unset()删除指定键,count()返回元素个数:

$num = [1, 3, 5, 7, 9]; $num[5] = 11; unset($num[2]); // 删除变量 print_r($num); # => 1 3 7 9 11 echo count($num); # => 5

注意:删除键后数组索引不会自动重排,count()反映的是剩余元素数量。查看: Arrays

运算符 Operators

$x = 1; $y = 2; $sum = $x + $y; echo $sum; # => 3

查看: Operators

Include

includerequire用于在脚本中引入其他文件,require在文件缺失时产生致命错误(E_COMPILE_ERROR),include仅产生警告(E_WARNING)后继续执行;二者也都支持函数式写法与返回值捕获:

vars.php
<?php // 以 PHP 开放标签开头。 $fruit = 'apple'; echo "I was imported"; return 'Anything you like.'; ?>
test.php
<?php include 'vars.php'; echo $fruit . "\n"; # => apple /* 与 include 相同, 如果不能包含则导致错误*/ require 'vars.php'; // 也有效 include('vars.php'); require('vars.php'); // 通过 HTTP 包含 include 'http://x.com/file.php'; // 包含和返回语句 $result = include 'vars.php'; echo $result; # => Anything you like. ?>

说明:通过 HTTP 包含远程文件依赖allow_url_include配置且存在安全风险,生产环境应避免使用;被包含文件若含return语句,则include表达式的结果即为该返回值。

功能 Functions

函数参数可以设置默认值,未传参时使用默认值:

function add($num1, $num2 = 1) { return $num1 + $num2; } echo add(10); # => 11 echo add(10, 5); # => 15

查看: Functions

注释 Comments

PHP 支持三种注释风格:

# 这是一个单行 shell 样式的注释 // 这是一行 c++ 风格的注释 /* 这是一个多行注释 另一行注释 */

常数 Constants

const在编译期定义,适合类常量与全局常量;echo MY_CONST直接输出常量值,字符串拼接时同样生效:

const MY_CONST = "hello"; echo MY_CONST; # => hello # => MY_CONST is: hello echo 'MY_CONST is: ' . MY_CONST;

类 Classes

__construct()是构造函数,$this指向当前实例:

class Student { public function __construct($name) { $this->name = $name; } } $alex = new Student("Alex");

查看: Classes

PHP 类型

布尔值 Boolean

true/false不区分大小写,也可用强制类型转换(boolean)将其他值转为布尔:

$boolean1 = true; $boolean2 = TRUE; $boolean3 = false; $boolean4 = FALSE; $boolean5 = (boolean) 1; # => true $boolean6 = (boolean) 0; # => false

布尔值不区分大小写。空字符串、"0"00.0[]null在布尔上下文中均为false

整数 Integer

支持十进制、八进制(前缀0)、十六进制(前缀0x)、二进制(前缀0b)以及自 PHP 7.4.0 起支持的数字分隔符_

$int1 = 28; # => 28 $int2 = -32; # => -32 $int3 = 012; # => 10 (octal) $int4 = 0x0F; # => 15 (hex) $int5 = 0b101; # => 5 (binary) # => 2000100000 (decimal, PHP 7.4.0) $int6 = 2_000_100_000;

另见: Integers

字符串 Strings

echo 'this is a simple string';

查看: Strings

数组 Arrays

$arr = array("hello", "world", "!");

查看: Arrays

浮点数 Float (Double)

支持科学计数法(e/E)与数字分隔符;PHP 会在数值上下文自动将数字字符串转换为数字参与运算:

$float1 = 1.234; $float2 = 1.2e7; $float3 = 7E-10; $float4 = 1_234.567; // as of PHP 7.4.0 var_dump($float4); // float(1234.567) $float5 = 1 + "10.5"; # => 11.5 $float6 = 1 + "-1.3e3"; # => -1299

Null

null表示变量无值;??为 null 合并运算符,左侧为null时返回右侧;=====的区别在于后者同时比较类型:

$a = null; $b = 'Hello php!'; echo $a ?? 'a is unset'; # => a is unset echo $b ?? 'b is unset'; # => Hello php $a = array(); $a == null # => true $a === null # => false is_null($a) # => false

空数组== nulltrue,但=== nullfalse,说明==会做类型宽松比较。

可迭代对象 Iterables

iterable类型(PHP 7.1+)可接受数组或实现了Traversable的对象,常与生成器(yield)配合:

function bar(): iterable { return [1, 2, 3]; } function gen(): iterable { yield 1; yield 2; yield 3; } foreach (bar() as $value) { echo $value; # => 123 }

PHP 字符串

字符串 String

单引号字符串不解析变量、不处理转义序列(\n\t按字面输出);双引号字符串会解析变量与转义序列:

# => '$String' $sgl_quotes = '$String'; # => 'This is a $String.' $dbl_quotes = "This is a $sgl_quotes."; # => a tab character. $escaped = "a \t tab character."; # => a slash and a t: \t $unescaped = 'a slash and a t: \t';

多行 Multi-line

Nowdoc(<<<'END')不执行插值,Heredoc(<<<END)会执行变量插值,适合书写大段文本:

$str = "foo"; // 未插值的多行 $nowdoc = <<<'END' Multi line string $str END; // 将执行字符串插值 $heredoc = <<<END Multi line $str END;

操作 Manipulation

常用字符串函数:strlen()长度、substr()截取(支持负偏移从尾部计数)、strtoupper()/strtolower()大小写、strpos()查找子串位置(找不到返回false,注意与0的严格比较):

$s = "Hello Phper"; echo strlen($s); # => 11 echo substr($s, 0, 3); # => Hel echo substr($s, 1); # => ello Phper echo substr($s, -4, 3);# => hpe echo strtoupper($s); # => HELLO PHPER echo strtolower($s); # => hello phper echo strpos($s, "l"); # => 2 var_dump(strpos($s, "L")); # => false

另见: 字符串函数

PHP 数组

定义

[]短数组语法与array()等价;explode()按分隔符拆分为数组:

$a1 = ["hello", "world", "!"] $a2 = array("hello", "world", "!"); $a3 = explode(",", "apple,pear,peach");
混合 int 和 string 键

数组键可为整数或字符串,二者可混用;整数键自动转换(如"100"转为100):

$array = array( "foo" => "bar", "bar" => "foo", 100 => -100, -100 => 100, ); var_dump($array);
短数组语法
$array = [ "foo" => "bar", "bar" => "foo", ];

多阵列

多维数组通过连续下标访问:

$multiArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; print_r($multiArray[0][0]) # => 1 print_r($multiArray[0][1]) # => 2 print_r($multiArray[0][2]) # => 3

多类型

同一数组中可混合字符串键、整数键与嵌套数组,var_dump()可查看值与类型详情:

$array = array( "foo" => "bar", 42 => 24, "multi" => array( "dim" => array( "a" => "foo" ) ) ); # => string(3) "bar" var_dump($array["foo"]); # => int(24) var_dump($array[42]); # => string(3) "foo" var_dump($array["multi"]["dim"]["a"]);

操作

$arr[] = value自动追加(键为当前最大整数键 + 1),sort()排序会重置键,unset()删除键或整个数组:

$arr = array(5 => 1, 12 => 2); $arr[] = 56; // 附加 $arr["x"] = 42; // 用键添加 sort($arr); // 排序 unset($arr[5]); // 消除 unset($arr); // 移除所有

查看: 数组函数

索引迭代

$array = array('a', 'b', 'c'); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "i:{$i}, v:{$array[$i]}\n"; }

价值迭代

$colors = array('red', 'blue', 'green'); foreach ($colors as $color) { echo "Do you like $color?\n"; }

关键迭代

foreach ($arr as $key => $value)同时取出键与值:

$arr = ["foo" => "bar", "bar" => "foo"]; foreach ( $arr as $key => $value ) { echo "key: " . $key . "\n"; echo "val: {$arr[$key]}\n"; }

串联阵列

自 PHP 7.4 起可使用展开运算符...合并数组(支持字符串键时行为略有不同,整数键会重新编号):

$a = [1, 2]; $b = [3, 4]; // PHP 7.4 以后 # => [1, 2, 3, 4] $result = [...$a, ...$b];

Into 函数

参数解包(Argument unpacking):...$array将数组元素按顺序展开为函数实参:

$array = [1, 2]; function foo(int $a, int $b) { echo $a; # => 1 echo $b; # => 2 } foo(...$array);

Splat运算符

可变参数(Variadic):...$other收集剩余实参为数组,可与类型声明组合使用:

function foo($first, ...$other) { var_dump($first); # => a var_dump($other); # => ['b', 'c'] } foo('a', 'b', 'c' /*, ...*/ ); // 或 function foo($first, string ...$other){}

PHP 运算符

算术

| 运算符 | 说明 | | :- | - | |+| 添加 | |-| 减法 | |*| 乘法 | |/| 分配(除法) | |%| 取模 | |**| 求幂(PHP 5.6+) |

分配

| 运算符 | 说明 | | :- | - | |a += b| 如同a = a + b| |a -= b| 如同a = a – b| |a *= b| 如同a = a * b| |a /= b| 如同a = a / b| |a %= b| 如同a = a % b|

比较

| 运算符 | 说明 | | :- | - | |==| 平等的(宽松比较) | |===| 完全相同的(严格比较,含类型) | |!=| 不相等 | |<>| 不相等(与!=等价) | |!==| 不相同 | |<| 少于 | |>| 比...更棒(大于) | |<=| 小于或等于 | |>=| 大于或等于 | |<=>| 小于/等于/大于(太空船运算符,返回 -1/0/1) |

逻辑的

| 运算符 | 说明 | | :- | - | |and| 和(优先级低于=) | |or| 或者(优先级低于=) | |xor| 独家或(异或) | |!| 不是(逻辑非) | |&&| 和(优先级高于and) | |\|\|| 或者(优先级高于or) |

实战提示:and/or的优先级低于赋值运算符,因此$r = true or false实际为($r = true) or false;需要严格优先级控制时优先使用&&/||

算术

// 算术 $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 $product = 2 * 2; // 4 $quotient = 2 / 1; // 2 // 速记算术 $num = 0; $num += 1; // 将 $num 增加 1 echo $num++; // 打印 1(评估后的增量) echo ++$num; // 打印 3(评估前的增量) $num /= $float; // 将商除并分配给 $num

注意$num++(先返回后自增)与++$num(先自增后返回)的区别。

按位

| 运算符 | 说明 | | :- | - | |&| 和(按位与) | |\|| 或(包括或,按位或) | |^| 异或(异或) | |~| 不是(按位非) | |<<| 左移 | |>>| 右移 |

PHP 条件

If elseif else

$a = 10; $b = 20; if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; }

Switch

switch使用宽松比较(==),多个case可共享同一执行块,break用于跳出:

$x = 0; switch ($x) { case '0': print "it's zero"; break; case 'two': case 'three': // do something break; default: // do something }

三元运算符

?:简写形式在条件为假时返回右侧值;??则仅在左侧为null时返回右侧:

# => Does print (false ? 'Not' : 'Does'); $x = false; # => Does print($x ?: 'Does'); $a = null; $b = 'Does print'; # => a is unsert echo $a ?? 'a is unset'; # => print echo $b ?? 'b is unset';

匹配

match表达式(PHP 8.0+)是switch的严格比较(===)升级版,作为表达式返回值,无需break,支持多条件用逗号合并:

$statusCode = 500; $message = match($statusCode) { 200, 300 => null, 400 => '未找到', 500 => '服务器错误', default => '已知状态码', }; echo $message; # => 服务器错误

查看: Match

匹配表达式

match (true)模式可替代多分支 if/elseif 链,实现区间判断:

$age = 23; $result = match (true) { $age >= 65 => 'senior', $age >= 25 => 'adult', $age >= 18 => 'young adult', default => 'kid', }; echo $result; # => young adult

PHP 循环

while 循环

$i = 1; # => 12345 while ($i <= 5) { echo $i++; }

do while 循环

先执行一次循环体再判断条件,因此至少执行一次:

$i = 1; # => 12345 do { echo $i++; } while ($i <= 5);

for i 循环

# => 12345 for ($i = 1; $i <= 5; $i++) { echo $i; }

break 跳出循环

break立即终止整个循环:

# => 123 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { break; } echo $i; }

continue 继续

continue跳过本次循环剩余代码,进入下一次迭代:

# => 1235 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { continue; } echo $i; }

foreach 循环

foreach遍历数组时,无键版本依次取每个元素的值:

$a = ['foo' => 1, 'bar' => 2]; # => 12 foreach ($a as $k) { echo $k; }

查看: Array iteration

PHP 函数

返回值

function square($x) { return $x * $x; } echo square(4); # => 16

返回类型

PHP 7.0+ 支持标量返回类型声明,7.1+ 支持对象返回类型:

// 基本返回类型声明 function sum($a, $b): float {/*...*/} function get_item(): string {/*...*/} class C {} // 返回一个对象 function getC(): C { return new C; }

可空返回类型

?string表示返回值既可以是string也可以是null(PHP 7.1+):

// 在 PHP 7.1 中可用 function nullOrString(int $v) : ?string { return $v % 2 ? "odd" : null; } echo nullOrString(3); # => odd var_dump(nullOrString(4)); # => NULL

查看: Nullable types

无效函数

void表示函数无返回值,可省略return或使用无值的return;(PHP 7.1+):

// 在 PHP 7.1 中可用 function voidFunction(): void { echo 'Hello'; return; } voidFunction(); # => Hello

变量函数

将函数名字符串赋给变量后直接以变量名调用,实现动态派发:

function bar($arg = '') { echo "In bar(); arg: '$arg'.\n"; } $func = 'bar'; $func('test'); # => In bar(); arg: test

匿名函数

闭包(Closure)可以赋值给变量、作为参数传递:

$greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); # => Hello World $greet('PHP'); # => Hello PHP

递归函数

函数在满足退出条件前不断调用自身:

function recursion($x) { if ($x < 5) { echo "$x"; recursion($x + 1); } } recursion(1); # => 1234

默认参数

未传参时使用默认值;显式传入null会覆盖默认值(可结合可空类型声明使用):

function coffee($type = "cappuccino") { return "Making a cup of $type.\n"; } # => 制作一杯卡布奇诺 echo coffee(); # => 制作一杯 echo coffee(null); # => 制作一杯浓缩咖啡 echo coffee("espresso");

箭头函数

箭头函数(PHP 7.4+)自动按值捕获外部变量,等价于use按值引入的匿名函数,语法更简洁:

$y = 1; $fn1 = fn($x) => $x + $y; // 相当于按值使用 $y: $fn2 = function ($x) use ($y) { return $x + $y; }; echo $fn1(5); # => 6 echo $fn2(5); # => 6

PHP 类

构造函数 Constructor

class Student { public function __construct($name) { $this->name = $name; } public function print() { echo "Name: " . $this->name; } } $alex = new Student("Alex"); $alex->print(); # => Name: Alex

继承 Inheritance

extends实现继承,parent::调用父类方法,子类可覆写(Override)父类方法:

class ExtendClass extends SimpleClass { // 重新定义父方法 function displayVar() { echo "Extending class\n"; parent::displayVar(); } } $extended = new ExtendClass(); $extended->displayVar();

类变量 Classes variables

可见性修饰符控制访问范围:public公开、protected仅类与子类、private仅限类内;static表示类级别共享,const定义类常量,均通过::访问:

class MyClass { const MY_CONST = 'value'; static $staticVar = 'static'; // 可见度 public static $var1 = 'pubs'; // 仅限类 private static $var2 = 'pris'; // 类和子类 protected static $var3 = 'pros'; // 类和子类 protected $var6 = 'pro'; // 仅限类 private $var7 = 'pri'; }

静态访问

echo MyClass::MY_CONST; # => value echo MyClass::$staticVar; # => static

魔术方法

__toString()定义对象被当作字符串使用时的输出;__destruct()在对象销毁时调用,与构造函数__construct()对应:

class MyClass { // 对象被视为字符串 public function __toString() { return $property; } // 与 __construct() 相反 public function __destruct() { print "Destroying"; } }

接口

接口定义契约,类通过implements实现一个或多个接口,必须实现接口声明的所有方法:

interface Foo { public function doSomething(); } interface Bar { public function doSomethingElse(); } class Cls implements Foo, Bar { public function doSomething() {} public function doSomethingElse() {} }

各种各样的

基本错误处理

try/catch/finallyfinally无论是否抛出异常都会执行:

try { // 做一点事 } catch (Exception $e) { // 处理异常 } finally { echo "Always print!"; }

PHP 8.0 中的异常

PHP 8.0 支持在表达式中直接throw,且catch可省略异常变量(仅捕获类型):

$nullableValue = null; try { $value = $nullableValue ?? throw new InvalidArgumentException(); } catch (InvalidArgumentException) { // 变量是可选的 // 处理我的异常 echo "print me!"; }

自定义异常

继承内置Exception类创建自定义异常类型,便于按类型分别捕获:

class MyException extends Exception { // 做一点事 }

用法

try { $condition = true; if ($condition) { throw new MyException('bala'); } } catch (MyException $e) { // 处理我的异常 }

Nullsafe 运算符

Nullsafe 运算符?->(PHP 8.0+)在链式调用中任一环节为null时直接短路返回null,避免冗长的逐层判空:

// 从 PHP 8.0.0 开始,这一行: $result = $repo?->getUser(5)?->name; // 相当于下面的代码: if (is_null($repo)) { $result = null; } else { $user = $repository->getUser(5); if (is_null($user)) { $result = null; } else { $result = $user->name; } }

另见: Nullsafe 运算符

常用表达

preg_match()使用 PCRE 正则匹配,返回匹配次数(0 或 1):

$str = "Visit jaywcjlove.github.io"; echo preg_match("/qu/i", $str); # => 1

查看: PHP中的正则表达式

该备忘仓库的 docs/regex.md 中还汇总了 PHP 正则的完整函数族:preg_match()匹配、preg_match_all()全局匹配、preg_replace()/preg_replace_callback()替换、preg_split()拆分、preg_grep()过滤数组,可直接作为正则开发的补充速查。

fopen() 模式

fopen()打开文件的模式决定读写方式与文件指针位置:

| 模式 | 说明 | | :- | - | |r| 读 | |r+| 读写,前置 | |w| 写入,截断 | |w+| 读写,截断 | |a| 写,追加 | |a+| 读写,追加 |

运行时定义的常量

define()在运行时定义常量,可用于依赖动态计算值(如日期)的常量:

define("CURRENT_DATE", date('Y-m-d')); // 一种可能的表示 echo CURRENT_DATE; # => 2021-01-05 # => CURRENT_DATE is: 2021-01-05 echo 'CURRENT_DATE is: ' . CURRENT_DATE;

另见

  • 本备忘清单在项目中的入口:README.md 中的 PHP 速查卡片;
  • 与 PHP 正则相关的完整速查见 docs/regex.md(PHP 中的正则表达式一节);
  • PHP 官方中文文档(php.net)
  • Learn X in Y minutes(learnxinyminutes.com)
  • 文档
  • 知识库
  • 教程
  • 开发工具

【免费下载链接】reference

为开发人员分享快速参考备忘清单(速查表)

项目地址:https://gitcode.com/jaywcjlove/reference
点击查看免费下载

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询