PHP code example of php-enspired / exceptable

1. Go to this page and download the library: Download php-enspired/exceptable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-enspired / exceptable example snippets




use at\exceptable\ {
  Error,
  IsError
};

// a simple Error, just for you
enum ProcessError : int implements Error {
  use IsError;

  case NotReady = 1;
  public const MESSAGES = [
    self::NotReady->name => "{type} is not ready (status is '{status}')"
  ];
}

class Example {
  public function __construct( public string $status ) {}
}

$example = new Example("preparing");
if ($example->status !== "ready") {
  throw (ProcessError::NotReady)([
    "type" => $example::class,
    "status" => $example->status
  ]);
}



use at\exceptable\ {
  Error,
  IsError
};

enum FooError : int implements Error {
  use IsError;

  case TheyToldMeToDoIt = 1;
  public const MESSAGES = [
    self::TheyToldMeToDoIt->name => "ooh noooooooooooooooooo!"
  ];
}

function foo(bool $fail) : string|FooError {
  return $fail ?
    FooError::TheyToldMeToDoIt :
    "woooooooooooooooooo hoo!";
}

$bool = maybeTrueMaybeFalse();
$result = foo($bool);
if ($result instanceof FooError) {
  echo $result->message();
  // outputs "ooh noooooooooooooooooo!"

  $bool = ! $bool;
  $result = foo($bool);
}

echo $result;
// outputs "woooooooooooooooooo hoo!"

throw $result(["yes" => "i know i'm horrible"]);