Skip to main content

Lesson 6 of 7

Object Cloning, Comparison & Value Objects

Understanding PHP's object identity model - how objects are compared and copied - is crucial for avoiding subtle bugs. Value Objects are immutable objects whose equality is based on their value, not their identity - ideal for modelling domain concepts like Email, Money, and DateRange.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Object Identity vs Equality & Value Objects

Object Identity vs Equality & Value Objects
<?php
declare(strict_types=1);

// ── Object assignment - reference semantics ────────────────────
$a = new stdClass();
$a->name = "Alice";
$b = $a;             // $b is NOT a copy - it's the same object
$b->name = "Bob";
echo $a->name;       // "Bob" - both refer to same object!

$c = clone $a;       // shallow copy - independent object
$c->name = "Carol";
echo $a->name;       // "Bob" - $a unchanged

// ── == vs === for objects ──────────────────────────────────────
$obj1 = new stdClass();
$obj1->val = 1;
$obj2 = new stdClass();
$obj2->val = 1;

var_dump($obj1 == $obj2);   // true - same class + same property values
var_dump($obj1 === $obj2);  // false - different instances

$obj3 = $obj1;
var_dump($obj1 === $obj3);  // true - same instance

// ── Value Object pattern - immutable, equality by value ────────
final class Email {
    private readonly string $value;

    public function __construct(string $email) {
        $email = strtolower(trim($email));
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException("Invalid email: $email");
        }
        $this->value = $email;
    }

    public function getValue(): string { return $this->value; }
    public function getDomain(): string { return explode("@", $this->value)[1]; }

    public function equals(self $other): bool {
        return $this->value === $other->value;
    }

    public function __toString(): string { return $this->value; }
}

final class Money {
    public function __construct(
        private readonly int    $cents,
        private readonly string $currency,
    ) {
        if ($cents < 0) throw new InvalidArgumentException("Amount cannot be negative.");
    }

    public function add(self $other): self {
        $this->assertSameCurrency($other);
        return new self($this->cents + $other->cents, $this->currency);
    }

    public function multiply(float $factor): self {
        return new self((int) round($this->cents * $factor), $this->currency);
    }

    public function equals(self $other): bool {
        return $this->cents === $other->cents && $this->currency === $other->currency;
    }

    private function assertSameCurrency(self $other): void {
        if ($this->currency !== $other->currency) {
            throw new InvalidArgumentException(
                "Currency mismatch: {$this->currency} vs {$other->currency}"
            );
        }
    }

    public function __toString(): string {
        return sprintf("%s %.2f", $this->currency, $this->cents / 100);
    }

    public static function USD(int $cents): self { return new self($cents, "USD"); }
    public static function EUR(int $cents): self { return new self($cents, "EUR"); }
}

// Value objects in action
$email1 = new Email("Alice@Example.COM");  // normalised to alice@example.com
$email2 = new Email("alice@example.com");
var_dump($email1->equals($email2));   // true

$price    = Money::USD(4999);          // $49.99
$tax      = $price->multiply(0.08);   // $4.00
$total    = $price->add($tax);        // $53.99
echo $total;   // "USD 53.99"

Quick Quiz

Tip

Tip

Practice Object Cloning Comparison Value Objects in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Object Cloning, Comparison & Value Objects

Practice Task

Note

Practice Task - (1) Write a working example of Object Cloning Comparison Value Objects from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Object Cloning Comparison Value Objects is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done