Menu
CoddyTech

静态方法与工厂

Coddy 面向 Go 开发者的 PHP 课程的第 34 课,共 48 课。

Go 通常使用包级函数作为工厂,而不是在类型上使用静态方法。PHP 静态方法属于类,并且没有 $this。工厂应明确说明其创建和验证策略,避免不必要地引入共享的可变静态属性。

静态方法通过类调用,并且没有 $this。它可以在没有现有实例的情况下验证或构造对象。使用 self:: 表示声明该方法的类,并在扩展工厂前了解 static:: 的后期静态绑定。静态属性是类共享的状态,不能替代对象字段。

Go 程序

package main
import ("fmt")
type Score struct{Points int}
func NewScore(points int)Score{return Score{Points:points}}

func main(){
fmt.Println(NewScore(7).Points)
}

源程序输出:

7

PHP 程序

demo.php

<?php
declare(strict_types=1);
class Units {public static function dozen():int{return 12;}} echo Units::dozen(),"\n";

PHP 输出:

12
challenge icon

挑战

简单

输入是一个非负整数,表示分钟数。Duration::minutes(int):Duration 根据分钟数构造秒数;seconds():int 读取该值。构造函数接受秒数。各个实例相互独立。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。请实现模块声明,不要打印内容;不要替换启动脚本,也不要从模块读取输入。输入符合所述类型和范围。

编辑 Duration.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Duration.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((new Duration(7))->seconds()===7 && Duration::minutes(3)->seconds()===180,"factory");
echo (string)Duration::minutes($input)->seconds(),"\n";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器