构造函数与验证
Coddy 面向 Ruby 开发者的 PHP 课程的第 30 课,共 48 课。
Ruby 的 Class#new 会调用 initialize,并返回新对象。PHP 的 new 会调用 __construct,还可以选择使用提升式类型化属性。Ruby 的 initialize 没有直接的属性提升语法;声明 PHP 类型仍不能替代领域验证。
__construct 会在 new 分配对象后对其进行初始化。构造函数属性提升可以通过在参数上使用可见性修饰符,同时声明并初始化属性。验证不变量,而不只是存储无效输入。如果子类声明了构造函数,并且需要进行父类初始化,请显式调用 parent::__construct。
Ruby 程序
class Tag
attr_reader :text
def initialize(text)
@text = text
end
end
puts Tag.new("draft").text源代码输出:
draftPHP 程序
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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 PHP中的所有课
自己练习: PHP 在线编译器