Golang Style Error Handling in PHP
Published on 2022-12-14
This is probably a bad idea as a generic solution for error handling in PHP, but it might have its uses in case you have a function that already has multiple return values.
<?php
declare(strict_types=1);
class Err
{
private string $err;
public function __construct(string $err = '')
{
$this->err = $err;
}
public function err(): string
{
return $this->err;
}
}
function fatalIfErr(?Err $err): void
{
if ($err !== null) {
echo 'ERROR: '.$err->err().PHP_EOL;
exit(1);
}
}
/**
* @return array{0:int,1:?Err}
*/
function myDiv(int $x, int $y): array
{
if ($y === 0) {
return [0, new Err('can not divide by zero')];
}
return [(int) ($x / $y), null];
}
[$res, $err] = myDiv(8, 4);
fatalIfErr($err);
echo $res.PHP_EOL;
UPDATE: added fatalIfErr
helper function.