Menu
CoddyTech

严格匹配表达式

Coddy 面向 C# 开发者的 PHP 课程的第 9 课,共 48 课。

C# switch 表达式支持类型模式、绑定和保护条件。PHP match 是一个表达式,使用严格的值比较,而不是 C# 模式匹配。PHP 的 int|string 参数联合类型会限制可接受的运行时类别,但无法复现 C# 的模式变量绑定。

PHP match 是一个表达式,它的分支使用严格的恒等比较。逗号用于分隔分支,并返回一个结果;不会发生贯穿执行。默认分支可以让任意输入都安全。如果没有匹配的分支或默认分支,PHP 会抛出 UnhandledMatchError。如果严格比较是约定的一部分,不要改用 switch。

C# 程序

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {

 static void Main() {
  object v="2";string result=v switch {int n when n==2=>"integer",string t when t=="2"=>"text",_=>"other"};Console.WriteLine(result);
 }
}

源程序输出:

text

PHP 程序

demo.php

<?php
declare(strict_types=1);
$v="2"; echo match($v){2=>"integer","2"=>"text",default=>"other"},"\n";

PHP 输出:

text
challenge icon

挑战

简单

输入是 JSON 整数或字符串。command 接受 int|string:整数 1 映射为 start,整数 0 映射为 stop,字符串 "1" 映射为 text-one,其他所有值都映射为 unknown。match 使用严格比较。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明时不要打印内容;不要替换启动器,也不要从模块读取输入。输入符合指定的类型和范围。

编辑 Functions.php。main.php 是锁定的入口文件。依赖项通过 require_once __DIR__ 和相对文件名引入。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(command(1)==="start" && command("1")==="text-one" && command("0")==="unknown","strict match");
echo command($input),"\n";
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器