- var_dump: documentation ( source)
- random_int: documentation ( source)
<?php
interface Entity
{
public function getId() : ?int;
}
class Comment implements Entity
{
private ?int $id = null;
private int $userId;
private string $text;
public function __construct(int $userId, string $text)
{
$this->userId = $userId;
$this->text = $text;
}
public function getId() : ?int
{
return $this->id;
}
public function setId(int $id) : void
{
$this->id = $id;
}
}
class PseudoDatabase {
private array $entities = [];
public function save(Entity $entity) {
$id = $entity->getId();
if (null === $id) {
$id = $this->generateId();
$entity->setId($id);
}
$this->entities[$id] = $entity;
}
private function generateId() : int
{
return random_int(1, 1000000);
}
}
$comment = new Comment(11, 'Test comment');
$database = new PseudoDatabase;
$database->save($comment);
var_dump($comment);