键、null 与存在性
Coddy 面向 C# 开发者的 PHP 课程的第 14 课,共 48 课。
C# 的 Dictionary.ContainsKey 和 TryGetValue 用于区分键是否存在,以及值是否为 null。缺少键时,C# 索引器会抛出异常。PHP 的 array_key_exists 用于测试键是否存在,而对于值为 null 的键,isset 会返回 false;读取 PHP 中缺失的键时,其诊断信息也与使用 Dictionary 索引不同。
使用 array_key_exists 来区分键不存在和值为 null 的情况。对于这两种情况,isset 都会返回 false。?? 也会将不存在的值和 null 值都视为需要使用备用值的情况。PHP 会将某些数字字符串键转换为整数;移植字典时,请限制键的类型范围,或考虑这种转换。
C# 程序
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
var a=new Dictionary<string,string?>{{"k",null}};Console.WriteLine(a.ContainsKey("k").ToString().ToLowerInvariant()+":"+(a["k"]!=null).ToString().ToLowerInvariant());
}
}源程序输出:
true:falsePHP 程序
demo.php
<?php
declare(strict_types=1);
$a=["k"=>null]; echo (array_key_exists("k",$a)?"present":"absent"),":",(isset($a["k"])?"set":"unset"),"\n";
PHP 输出:
present:unset挑战
简单输入是一个对象,其中包含字符串字段或 null 值,以及一个键:[mapping,key]。如果键不存在,lookup 会返回 missing;如果键存在且值为 null,则返回 null-value;如果值是字符串,则返回 value:TEXT。请将键是否存在与值是否为 null 分开处理。
提供的主脚本会从标准输入读取一个 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(lookup(["x"=>null],"x")==="null-value" && lookup([],"x")==="missing","presence");
echo lookup(...$input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 PHP中的所有课
自己练习: PHP 在线编译器