Menu
CoddyTech

Reference Lifetimes

Lesson 40 of 48 in Coddy's GDScript for PHP Developers course.

PHP combines reference counting with cyclic garbage collection. Godot RefCounted counts strong references but does not automatically reclaim strong-reference cycles. PHP WeakReference and Godot WeakRef observe without retaining their objects. Clearing one variable leaves an object alive when another strong reference still designates it. Godot Nodes have a separate lifecycle and should not be treated as RefCounted data objects.

Complete PHP 8.3 program files (run main.php with the CLI):

PHP file Item.php:

<?php
declare(strict_types=1);
class Item {}

PHP file main.php:

<?php
declare(strict_types=1);
require_once __DIR__."/Item.php"; $a=new Item(); $weak=WeakReference::create($a); $b=$a; $a=null; echo json_encode($weak->get()===$b),"\n";

PHP output:

true

Complete GDScript example files:

GDScript file main.gd:

extends Node

func _ready() -> void:
	var a: RefCounted = RefCounted.new()
	var weak: WeakRef = weakref(a)
	var b: RefCounted = a
	a = null
	print(weak.get_ref() == b)

GDScript output:

true
challenge icon

Challenge

Easy

Implement OwnedNote(text:String) and static NoteViews.label(note:OwnedNote)->String. Return missing for null; otherwise return note.text. Solve creates a note for a string input, or passes null. Do not manually free RefCounted instances.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in owned_note.gd, note_views.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var original: OwnedNote = OwnedNote.new("a")
	var alias: OwnedNote = original
	original = null
	if NoteViews.label(alias) != "a" or NoteViews.label(null) != "missing": 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 iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for PHP Developers

Practice on your own: Online GDScript compiler