- filter_var: documentation ( source)
- compact: documentation ( source)
- json_encode: documentation ( source)
<?php
class Email implements JsonSerializable
{
private $value;
public function __construct(string $value)
{
$email = filter_var($value, FILTER_VALIDATE_EMAIL);
if (false === $email) {
throw new Exception('Email is invalid.');
}
$this->value = $email;
}
public function jsonSerialize()
{
return $this->value;
}
}
$email = new Email('opexus@gmail');
echo json_encode(compact('email'));