Created
May 16, 2022 13:50
-
-
Save esdras-schonevald/71a6730e6191c5e9c053e2f65b839eec to your computer and use it in GitHub Desktop.
PHP ^8.1 ENUM - HOW TO USE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
/** | |
* This is a sample | |
* How to use Enum to create a custom exception cases | |
* PHP 8.1^ | |
*/ | |
enum MyExceptionCase { | |
case InvalidMethod; | |
case InvalidProperty; | |
case Timeout; | |
} | |
class MyException extends Exception { | |
function __construct(private MyExceptionCase $case){ | |
match($case){ | |
MyExceptionCase::InvalidMethod => parent::__construct("Bad Request - Invalid Method", 400), | |
MyExceptionCase::InvalidProperty => parent::__construct("Bad Request - Invalid Property", 400), | |
MyExceptionCase::Timeout => parent::__construct("Bad Request - Timeout", 400) | |
}; | |
} | |
} | |
// Testing my custom exception class | |
try { | |
throw new MyException(MyExceptionCase::InvalidMethod); | |
} catch (MyException $myE) { | |
echo $myE->getMessage(); // Bad Request - Invalid Method | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it should be
public function __construct
and it can letMyException
class constructor have been visible.