Menu
CoddyTech

默认值和命名调用

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

C# 和 PHP 都支持使用冒号语法的命名参数,以及可选参数的默认值。在这两种语言中,参数名称对调用方都可能很重要。C# 在编译时解析重载;PHP 不支持仅通过参数签名区分的等效重载集合。

省略参数时会使用默认参数值。命名参数使用 parameterName: value;因此,参数名称会成为可调用 API 的一部分。位置参数要放在命名参数之前。即使函数仍接受相同的位置参数类型,更改参数名称也可能导致调用方出错。

C# 程序

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

class Program {
static string Stamp(string text,string mark="!"){return text+mark;}
 static void Main() {
  Console.WriteLine(Stamp(mark:"?",text:"why"));
 }
}

源代码输出:

why?

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,并返回两者的乘积。驱动程序会打印默认调用和显式调用的结果,并在第二次调用时使用命名参数 quantity。

提供的 main 脚本会从标准输入读取一个 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 在线编译器