use*_*841 2 php oop class-constants
我有一个php类,其中包含一些表示实例状态的类常量.
当我使用该类时,在我运行一些方法之后,我会做一些检查以确保状态是我期望的.
例如,在调用某些方法之后,我希望状态为MEANINGFUL_STATUS_NAME.
$objInstance->method1();
$objInstance->method2();
if ( $objInstance->status !== class::MEANINGFUL_STATUS_NAME ) {
throw new Exception("Status is wrong, should not be " . class::MEANINGFUL_STATUS_NAME . ".");
}
Run Code Online (Sandbox Code Playgroud)
但是,这给了我异常消息
"Status is wrong, should not be 2"
Run Code Online (Sandbox Code Playgroud)
当我真正想看到的是
"Status is wrong, should not be MEANINGFUL_STATUS_NAME"
Run Code Online (Sandbox Code Playgroud)
所以我失去了常名的意义.我正在考虑制作一个"转换表"数组,所以我可以将常量值转换回它们的名称,但这看起来很麻烦.我应该如何翻译它,所以我收到一条错误消息,让我更好地了解出了什么问题?
这是一个棘手的解决方案:
$r = new ReflectionClass("YourClassName");
$constantNames = array_flip($r->getConstants());
$objInstance->method1();
$objInstance->method2();
if ( $objInstance->status !== YourClassName::MEANINGFUL_STATUS_NAME ) {
throw new Exception("Status is wrong, should not be " . $constantNames[YourClassName::MEANINGFUL_STATUS_NAME] . ".");
}
Run Code Online (Sandbox Code Playgroud)