Menu
CoddyTech

Null 不是假值

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

C# 的可空引用注解用于编译器分析,并不是单独的运行时字符串类型。像 int? 这样的可空值类型则不同。PHP 的 ?string 是包含 null 的运行时类型联合。PHP 的 ?? 会保留空字符串,而 ?: 使用更广泛的假值集合。

?string 是 string|null 的简写。?? 仅在值为 null 或未定义时选择备用值;?: 使用一般的真值判断。如果值包含空文本、零或字符串 0,这两者的行为就不同。只要业务领域有此要求,就要区分缺失值和有效的空结果。

C# 程序

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

class Program {

 static void Main() {
  string? s="";Console.WriteLine((s??"fallback")+":"+string.IsNullOrEmpty(s).ToString().ToLowerInvariant());
 }
}

源程序输出:

:true

PHP 程序

demo.php

<?php
declare(strict_types=1);
$s="0"; echo ($s??"fallback"),":",($s?:"fallback"),"\n";

PHP 输出:

0:fallback
challenge icon

挑战

简单

输入是字符串或 null。displayName 只在值为 null 时返回 guest,空文本和字符串 0 都会保留。

提供的主脚本会从标准输入读取一个 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(displayName("")==="" && displayName("0")==="0" && displayName(null)==="guest","null-only fallback");
echo displayName($input),"\n";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器