Menu
CoddyTech

分支与优先级

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

C 和 PHP 都支持大括号、&&、|| 以及使用 ?: 进行的条件选择。PHP 还额外提供了低优先级的 and/or 运算符,其分组方式与 && 和 || 不同。请保留括号和每个边界,不要假定类似的拼写就代表相同的完整表达式。

使用大括号表示分支,并使用圆括号使组合规则更加明确。&& 的绑定优先级高于 ||。三元表达式用于选择一个值;PHP 的写法为 condition ? yes : no。当任意分支需要多条语句时,优先使用普通的 if 语句。条件应该测试领域规则,而不是附带的字符串格式化。

C 程序

#include <stdio.h>

int main(void)
{
    int n = 10;
    if (0 <= n && n <= 10) {
        puts("in");
    } else {
        puts("out");
    }
    return 0;
}

源输出:

in

PHP 程序

demo.php

<?php
declare(strict_types=1);
$n=4; echo $n>3?"high":"low"; echo "\n";

PHP 输出:

high
challenge icon

挑战

简单

输入为 [age, credit, member]。age 范围为 0..120,credit 范围为 0..1000,member 为布尔值。eligible 要求 age 至少为 18,并且 credit 至少为 10 或具备会员身份。

提供的主脚本从标准输入读取一个 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(!eligible(10,100,true) && eligible(19,0,true),"eligible");
echo eligible(...$input)?"eligible":"blocked","\n";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器