PHP 关键字与语言特性详解

PHP 关键字与保留字字典:含语言关键字、运算符级惯用与 8.x 新语法。逐条给语义与示例。

1. abstract – 抽象

描述

抽象类不能实例化;抽象方法只有签名,子类必须实现。

语法和示例

abstract class Repo {
    abstract public function find(int $id): ?object;
    public function all(): array { return $this->query('SELECT *'); }
    abstract protected function query(string $sql): array;
}

2. and / or / xor(与 && || 的区别)

描述

优先级极低:赋值之后才运算——推荐永远用 && / ||。

语法和示例

$a = true or die();     // or 生效于赋值后(老惯用法)
$a = true || die();     // || 先于赋值,die 不执行
true xor true;          // 异或:一真一假才真

3. array – 数组字面量

描述

PHP 数组是有序映射;短语法 [] 与 array() 等价。

语法和示例

$list = [1, 2, 3];
$map = ['go' => 1, 'php' => 2];
$nested = ['a' => [1, 2]];
[] === $empty;                 // 空数组比较
compact('a', 'b');              // 变量打包成数组

4. as – foreach 别名与 trait 冲突调整

描述

foreach 的键值绑定;trait 同名方法的 insteadof/as。

语法和示例

foreach ($items as $key => $val) {}
foreach ($items as $val) {}
// trait 冲突:
class C {
    use A, B {
        A::foo insteadof B;
        B::foo as bar;         // 改名保留
    }
}

5. break / continue – 跳出

描述

可选层级参数跳出多层;continue 也接受层级。

语法和示例

foreach ($matrix as $row) {
    foreach ($row as $v) {
        if ($v === 0) continue 2;   // 跳到外层下一轮
        if ($v < 0) break 2;         // 全部跳出
    }
}

6. callable / Closure – 回调类型

描述

callable 类型提示收函数名/闭包/[$obj,’method’];Closure 是闭包类。

语法和示例

function run(callable $fn): void { $fn(); }
run('strlen');                       // 函数名
run([$this, 'handler']);             // 方法
run(fn() => print 'hi');              // 箭头函数
$f = function ($x) use ($factor) {   // use 显式捕获
    return $x * $factor;
};
$arrow = fn($x) => $x * $factor;     // 箭头自动捕获

7. class / new / extends / implements

描述

类声明四件;::class 取全限定名(免字符串)。

语法和示例

namespace App;
class Service extends Base implements Iface {}
Service::class;               // 'App\Service'
$instance = new Service();
$class = Service::class;
new $class();                  // 动态实例化

8. const / define – 常量

描述

const 编译期(类内必须用它);define 运行期;常量全局无 $。

语法和示例

const MAX = 100;
define('APP_VER', '2.1');
class C { const LIMIT = 5; }         // 类常量
C::LIMIT;  MAX;                       // 使用无 $
// 8.3+ 类常量可带类型:const int LIMIT = 5;

9. declare – 指令块

描述

strict_types 必须第一条;ticks 少用。

语法和示例

<?php
declare(strict_types=1);
function add(int $a, int $b): int { return $a + $b; }
add('1', 2);   // TypeError(默认模式会静默转换)

10. echo / print – 输出

描述

echo 语言结构(可逗号多参);print 是表达式返回 1。

语法和示例

echo 'a', 'b';        // 多参数
print 'x';             // 表达式:$r = print 'x';
printf('%05.2f', 3.1); // 格式化输出

11. enum(8.1+)

描述

纯枚举或 backed(int/string);自带 cases/from/tryFrom;可实现接口/含方法。

语法和示例

enum Status: string {
    case Draft = 'draft';
    case Published = 'published';
    public function label(): string {
        return match($this) {
            self::Draft => '草稿',
            self::Published => '已发布',
        };
    }
}
Status::cases();            // 全部枚举项
Status::from('draft');      // 不存在抛 ValueError
Status::tryFrom('x');       // null

12. extends 继承与 final

描述

单继承;final 类不可继承、final 方法不可覆盖。

语法和示例

class Base { public function run(): void {} }
final class Locked extends Base {
    final public function run(): void {}   // 子类到此为止
}

13. fn(7.4+)- 箭头函数

描述

自动按值捕获外部变量;单表达式。

语法和示例

$factor = 3;
$mul = fn($x) => $x * $factor;       // 等价 use($factor)
usort($items, fn($a, $b) => $a <=> $b);   // 飞船排序

14. function / return / 类型声明

描述

参数类型、返回类型(含 void/never)、可空 ?T、联合 A|B(8.0+)、交叉 A&B(8.1+)。

语法和示例

function div(int|float $a, int|float $b): int|float {
    if ($b === 0) throw new ValueError('除零');
    return $a / $b;
}
function log2(string $m): void { error_log($m); }
function fail(): never { throw new RuntimeException(); }   // 8.1+
function find(int $id): ?User {}                            // 可空返回
function handle(Countable&Iterator $c): void {}             // 交叉类型

15. global / static 变量

描述

global 引入全局(不推荐);static 在函数调用间保持值。

语法和示例

$count = 0;
function bump(): void { global $count; $count++; }
function counter(): int {
    static $n = 0;              // 跨调用保持
    return ++$n;
}

16. implements / interface

描述

接口定义方法契约;常量可定义;属性不可。

语法和示例

interface Runnable {
    public const VERSION = '1';
    public function run(): void;
}
class Job implements Runnable {
    public function run(): void {}
}
Job instanceof Runnable;   // true

17. instanceof – 类型判断

描述

判断对象是否某类/接口;右侧可为变量类名。

语法和示例

if ($e instanceof TypeError) {}
$obj instanceof $className;        // 动态类名

18. list / [] 解构

描述

按位置或键解构;跳过用空位。

语法和示例

[$a, $b] = [1, 2];
[, $second] = ['x', 'y'];
['id' => $id, 'name' => $name] = $row;
foreach ($points as [$x, $y]) {}

19. match(8.0+)- 匹配表达式

描述

严格 ===、无 fall-through、是表达式;条件模式用 match(true)。

语法和示例

$msg = match($code) {
    200, 201 => '成功',
    404 => '未找到',
    default => '其他',
};
$type = match(true) {                 // 条件分发
    $age < 18 => '未成年',
    $age < 60 => '在职',
    default => '退休',
};

20. namespace / use – 命名空间

描述

PSR-4 目录映射;use 引入+别名;函数/常量 use function/use const。

语法和示例

namespace App\Service;
use App\Model\User;
use App\Model\{Order, Item};        // 组导入
use function App\Util\format;
use const App\Util\LIMIT;
use App\Model\User as U;
new \DateTimeImmutable();             // 全局限定开头 \

21. private / protected / public – 可见性

描述

对象级可见(同类的不同实例可互访私有——与 Java 不同)。

语法和示例

class Wallet {
    private int $balance = 0;                    // 属性类型声明
    public function __construct(private readonly string $owner) {}   // 提升
    public function transferFrom(Wallet $other, int $n): void {
        $other->balance -= $n;      // 同类实例可访问私有!
        $this->balance += $n;
    }
}

22. readonly(8.1+)/ readonly 类(8.2+)

描述

一次初始化后不可写;readonly class 全属性只读。

语法和示例

class P {
    public function __construct(public readonly int $x) {}
}
$p = new P(1);
// $p->x = 2;   // Error:不可写
readonly class Config {                     // 8.2+
    public function __construct(public string $env) {}
}

23. static – 静态成员与方法

描述

属于类;self/static 后期静态绑定差异。

语法和示例

class A {
    public static string $name = 'A';
    public static function who(): string { return static::class; }  // 后期绑定
}
class B extends A {}
echo B::who();        // 'B'(static::)—— self:: 则是 'A'
A::$name; new static();   // new static 在工厂模式常用

24. throw / try / catch / finally

描述

多类型 catch(7.1+);finally 总执行;异常链。

语法和示例

try {
    risky();
} catch (TypeError | ValueError $e) {       // 多类型
    // PHP 8 引擎异常也走这里
} catch (Exception $e) {
    throw new AppException('包装', previous: $e);   // 命名参数传链(8.0+)
} finally {
    cleanup();      // return 之前也执行
}

25. trait – 横向复用

描述

方法集注入;可含属性/抽象方法;冲突见 as 条。

语法和示例

trait Timestampable {
    public ?string $createdAt = null;
    public function touch(): void {
        $this->createdAt = date('c');
    }
}
class Post { use Timestampable; }

26. null 合并与三目简写

描述

?? 左侧 null 才取右(isset 语义,不报未定义);?: 弱判断 falsy。

语法和示例

$name = $input['name'] ?? '默认';     // 键不存在也不报错
$page = $_GET['page'] ?? 1;
$a = $x ?: '默认';                      // falsy(0/''/null)都取右——与 ?? 不同!
$deep = $a['b']['c'] ?? null;           // 链式安全

27. 太空船 与比较运算符

描述

三路比较返回 -1/0/1,usort 标配。

语法和示例

1 <=> 2;      // -1
2 <=> 1;      // 1
usort($items, fn($a, $b) => $a['age'] <=> $b['age']);

28. 字符串插值与定界符

描述

双引号解析 $var 与 {$expr};单引号原样;Heredoc 多行。

语法和示例

$name = 'World';
"Hello $name";            // 解析
"Total: {$order->total}"; // 复杂表达式加大括号
'Skip \n $name';          // 原样(仅 \' 与 \\ 转义)
$sql = <<<'SQL'            // Nowdoc(单引号:不插值)
SELECT * FROM t WHERE id = :id
SQL;
$text = <<<TXT             // Heredoc(插值)
值为 $name
TXT;
暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇