构造函数与验证
Coddy 面向 C++ 开发者的 PHP 课程的第 30 课,共 48 课。
C++ 构造函数和成员初始化列表用于设置对象状态,并且在输入无效时可以抛出异常。PHP 的 __construct 和属性提升可以初始化已声明的属性,但属性提升不会验证领域规则。拒绝会导致对象无法正常使用的值。
__construct 会在 new 分配对象后对其进行初始化。构造函数属性提升可以通过参数上的可见性修饰符同时声明并初始化属性。要验证不变量,而不只是存储无效输入。如果子类声明了构造函数,并且需要进行父类初始化,请显式调用 parent::__construct。
C++ 程序
#include <iostream>
#include <stdexcept>
struct Score {int points;explicit Score(int value):points(value){if(value<0)throw std::invalid_argument("negative");}};
int main() {
Score score(3);std::cout<<score.points<<"\n";
}
源程序输出:
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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 PHP中的所有课
自己练习: PHP 在线编译器