Menu
CoddyTech

默认参数与命名参数

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

标准 C 没有默认参数或具名函数参数,因此通常使用包装器或配置结构体来表达这些 API。PHP 支持声明默认值和具名参数,这使得参数名称成为了公共调用约定的一部分。请注意区分省略参数与显式传入零或 false 值的情况。

当省略参数时,会使用默认参数值。具名参数使用 parameterName: value 形式;因此参数名称会成为可调用 API 的一部分。请将位置参数放在具名参数之前。即使函数仍然接收相同的位置类型,修改参数名称也可能破坏调用方的代码。

C 程序

#include <stdbool.h>
#include <stdio.h>
struct Options { bool has_repetitions; int repetitions; };
static int repetitions(struct Options options) {
    return options.has_repetitions ? options.repetitions : 2;
}
int main(void) {
    struct Options missing = {false, 0};
    struct Options zero = {true, 0};
    printf("%d:%d\n", repetitions(missing), repetitions(zero));
    return 0;
}

源输出:

2:0

PHP 程序

demo.php

<?php
declare(strict_types=1);
function stamp(string $text,string $mark="!"):string{return $text.$mark;} echo stamp(mark:"?",text:"why"),"\n";

PHP 输出:

why?
challenge icon

挑战

简单

输入为非负整数 [price, quantity]。cost 函数的 quantity 默认值为 1,并返回它们的乘积。主程序打印 default:explicit,第二次调用时使用命名 quantity 参数。

提供的主脚本从标准输入读取一个 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(cost(4)===4 && cost(quantity:3,price:5)===15,"named defaults");
echo cost($input[0]).":".cost(price:$input[0],quantity:$input[1]),"\n";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器