Menu
CoddyTech

Object handles and identity

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

GDScript Object equality distinguishes separate instances even when their fields look equal; value-like collections follow their own comparison rules. PHP === checks object identity, while == compares class and properties. Choose identity when shared mutation or registry membership depends on the exact instance.

Assigning an object variable copies an object identifier, so both variables can access the same object. Reassigning one variable does not reassign the other. === tests object identity; == compares object properties and class according to PHP object comparison rules. Choose identity when verifying shared collaborators.

GDScript program

extends SceneTree
class Marker:
    var value = 4

func _init():
    var a = Marker.new()
    var b = Marker.new()
    var alias = a
    print(str(a == alias) + ":" + str(a == b))
    quit()

Source output:

true:false

PHP program

demo.php

<?php
declare(strict_types=1);
class Marker {public function __construct(public int $id){}} $a=new Marker(4);$b=new Marker(4);echo ($a===$b?"same":"different"),"\n";

PHP output:

different
challenge icon

Challenge

Easy

Input is an integer. Cell has public int value initialized through its constructor. bump(Cell):void increases value by one. Driver aliases the object, calls bump on alias and prints original value. No replacement object.

The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.

Edit Cell.php, Functions.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.

Try it yourself

<?php
declare(strict_types=1);
require_once __DIR__."/Cell.php";
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function cellReport(int $n):int{$c=new Cell($n);$alias=$c;bump($alias);return $c->value;}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$c=new Cell(7);$alias=$c;bump($alias);ensure($c===$alias && $c->value===8,"shared handle");
echo (string)cellReport($input),"\n";
quiz iconTest yourself

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

All lessons in PHP for GDScript Developers

Practice on your own: Online PHP compiler