Value Objects

Learn about value objects and their implications.

Overview

A value object is an abstract data type wherein each object represents an entity: the value. The grounds for a comparison of value objects is their value, not the identity of the object. The code below demonstrates this.

Code example

Press + to interact
<?php
class HttpMessage
{
private int $code;
private string $response;
public function __construct(int $code, string $response)
{
$this->code = $code;
$this->response = $response;
}
public function verify(HttpMessage $message) : bool
{
return $this->response == $message->response &&
$this->code == $message->code;
}
public function newMessage(int $code, string $response) : HttpMessage
{
$newMessage = clone $this;
$newMessage->code = $code;
$newMessage->response = $response;
return $newMessage;
}
}
$ok = new HttpMessage(200, 'OK');
$created = $ok->newMessage(201, 'OK');
echo $ok->verify($created) ?
'Value objects are equal' :
'Value objects are not equal';

The class above is instantiable as an HTTP message value object. It ...