构造函数与验证
Coddy 面向 Kotlin 开发者的 PHP 课程的第 30 课,共 48 课。
Kotlin 的主构造函数和 init 代码块可以初始化属性,并使用 require 强制执行约束。PHP 的 __construct 和属性提升可以存储构造函数参数,但不会自动验证业务不变量。在公开实例之前,拒绝不可用的状态。
new 分配对象后,__construct 会对其进行初始化。构造函数属性提升可以在参数上使用可见性修饰符,同时声明并初始化属性。要验证不变量,而不是只存储无效输入。如果子类声明了构造函数,并且需要父类初始化,请显式调用 parent::__construct。
Kotlin 程序
class Score(val points:Int){init{require(points>=0)}}
fun main(){
println(Score(3).points)
}
源代码输出:
3PHP 程序
demo.php
<?php
declare(strict_types=1);
class Tag {public function __construct(public string $text){}} $t=new Tag("draft"); echo $t->text,"\n";
PHP 输出:
draft挑战
简单输入是一个整数。Capacity 构造函数接受非负的 limit,遇到负数时会抛出 InvalidArgumentException。limit():int 会返回该值。对于被拒绝的构造,驱动程序会输出 invalid。
提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。请实现模块声明,不要输出内容;不要替换启动程序,也不要从模块中读取输入。输入符合指定的类型和范围。
编辑 Capacity.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Capacity.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function capacityReport(int $n):string{try{return (string)(new Capacity($n))->limit();}catch(InvalidArgumentException $e){return "invalid";}}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Capacity(3))->limit()===3,"constructor value");try{new Capacity(-2);throw new RuntimeException("accepted negative");}catch(InvalidArgumentException $e){}
echo capacityReport($input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 PHP中的所有课
自己练习: PHP 在线编译器