Menu
CoddyTech

Object handles and identity

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

JavaScript === compares object identity, as PHP === does for objects. JavaScript == also compares object identity when both operands are objects, while PHP == generally compares properties and class. Do not use PHP == as a drop-in object identity check.

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.

JavaScript program

const a={id:4}, b={id:4}; console.log(a===b?"same":"different");

Source output:

different

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 JavaScript Developers

Practice on your own: Online PHP compiler