Menu
CoddyTech

객체 합성

Coddy의 PHP 개발자를 위한 GDScript 코스 레슨. 48개 중 29번째.

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 = value

GDScript 파일 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
challenge icon

챌린지

쉬움

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))
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

PHP 개발자를 위한 GDScript의 모든 레슨

직접 연습해 보세요: 온라인 GDScript 컴파일러