A constants component for PHP.
composer require huangdijia/constants
- Before
class ErrorCode
{
const NOT_FOUND = 404;
const SERVER_ERROR = 500;
public static $errors = [
self::NOT_FOUND => 'Not Found',
self::SERVER_ERROR => 'Server Error',
];
public static function getMessage($code)
{
return self::$errors[$code] ?? '';
}
}
- Now
namespace App\Constants;
use Huangdijia\Constants\AbstractConstants;
/**
* @method static string getMessage(string $code)
* @method static string getMessageCn(string $code)
* @method static string getMessageEn(string $code)
*/
class ErrorCode extends AbstractConstants
{
/**
* @Message("%s not found!")
*/
const NOT_FOUND = 404;
/**
* @Message("Server Error")
*/
const SERVER_ERROR = 500;
/**
* @MessageCn("成功")
* @MessageEn("Success")
*/
const OK = 1;
/**
* @MessageCn("失败")
* @MessageEn("Failure")
*/
const FAILURE = 0;
}
var_dump(ErrorCode::getMessage(ErrorCode::SERVER_ERROR)); // Server Error
var_dump(ErrorCode::getMessage(ErrorCode::NOT_FOUND, '/api')); // /api not found!
var_dump(ErrorCode::getMessageCn(ErrorCode::OK)); // 成功
var_dump(ErrorCode::getMessageEn(ErrorCode::OK)); // Success