分支与优先级
Coddy 面向 GDScript 开发者的 PHP 课程的第 8 课,共 48 课。
GDScript 使用缩进和 elif,并支持短路布尔表达式以及条件值表达式。PHP 使用花括号、elseif 和 ?:。PHP 对 and/or 与 &&/|| 的优先级也有不同规定,因此要保留预期的分组方式和每个边界比较。
分支使用花括号,并用括号明确组合规则。&& 的优先级高于 ||。三元表达式用于选择一个值;PHP 的写法是 condition ? yes : no。如果任一分支需要执行多条语句,最好使用常规的 if。条件应检查领域规则,而不是字符串格式等偶然因素。
GDScript 程序
extends SceneTree
func _init():
var temperature = 20
if temperature < 0:
print("cold")
elif temperature <= 20:
print("mild")
else:
print("hot")
quit()源程序输出:
mildPHP 程序
demo.php
<?php
declare(strict_types=1);
$n=4; echo $n>3?"high":"low"; echo "\n";
PHP 输出:
high挑战
简单输入为 [age, credit, member]。年龄范围为 0..120,信用额度范围为 0..1000,member 为布尔值。eligible 要求年龄至少为 18,并且信用额度至少为 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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 GDScript 开发者的 PHP中的所有课
自己练习: PHP 在线编译器