组合对象
Coddy 面向 PHP 开发者的 GDScript 课程的第 29 课,共 48 课。
PHP 中值为对象的属性和 GDScript 对象字段可以共享同一个协作者。复制对象标识符不会克隆实例,因此之后通过另一个别名进行的更改仍然可见。PHP 的 clone 是单独的操作,不会递归复制每个被引用的对象。构造函数注入让行为可以替换。PHP 有循环垃圾回收机制;RefCounted 的强引用循环需要明确设计所有权或使用弱链接。
完整的 PHP 8.3 程序文件(使用 CLI 运行 main.php):
PHP 文件 Note.php:
<?php
declare(strict_types=1);
class Note { public string $text="a"; }
PHP 文件 Envelope.php:
<?php
declare(strict_types=1);
class Envelope { public function __construct(public Note $note) {} }
PHP 文件 main.php:
<?php
declare(strict_types=1);
require_once __DIR__."/Note.php"; require_once __DIR__."/Envelope.php"; $n=new Note(); $e=new Envelope($n); $n->text="b"; echo $e->note->text,"\n";
PHP 输出:
b完整的 GDScript 示例文件:
GDScript 文件 demo_note.gd:
class_name DemoNote
extends RefCounted
var text: String = "a"GDScript 文件 demo_envelope.gd:
class_name DemoEnvelope
extends RefCounted
var note: DemoNote
func _init(value: DemoNote) -> void:
note = valueGDScript 文件 main.gd:
extends Node
func _ready() -> void:
var note: DemoNote = DemoNote.new()
var envelope: DemoEnvelope = DemoEnvelope.new(note)
note.text = "b"
print(envelope.note.text)GDScript 输出:
b挑战
简单实现 RateRule(cents:int),并提供 cost(units:int)。BillBox(rule:RateRule) 保存传入的规则,total(units:int) 则委托该规则处理。之后修改 rule.cents 必须影响账单。Solve 使用 [rate,units]。
输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公共 API,并打印 result=,后面跟着返回的文本和一个换行符。任何辅助函数都不应打印内容。输入用例之前,会通过独立的固定探测验证必需的 API 行为;这些探测不会限制实现风格。
你的代码应写在 rate_rule.gd、bill_box.gd 和 exercise.gd 中。main.gd 包含提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在与其同名的文件中。
亲手试试
extends Node
func contract_ok(data: Array) -> bool:
var rule: RateRule = RateRule.new(2)
var bill: BillBox = BillBox.new(rule)
rule.cents = 7
if rule.cost(3) != 21 or bill.total(3) != 21: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器