2

I have a php class with some class constants that indicate the status of an instance.

When I'm using the class, after I run some methods on it, I do some checks to make sure that the status is what I expect it to be.

For instance, after calling some methods, I expect the status to be 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 . ".");
}

However, this gives me the exception message

"Status is wrong, should not be 2"

when what I really want to see is

"Status is wrong, should not be MEANINGFUL_STATUS_NAME"

So I've lost the meaningfulness of the constant name. I was thinking of making an 'translation table' array, so I can take the constant values and translate them back into their name, but this seems cumbersome. How should I translate this back, so I get an error message that gives me a better idea of what went wrong?

4

3 に答える 3

6

これはちょっと難しい解決策です:

$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] . ".");   
} 
于 2010-05-18T18:46:11.167 に答える
1

定数の値として文字列を使用できることを思いつきました。数字を見るのに慣れてきました。これを行うべきではない理由、またはこれが機能しない理由はありますか?

于 2010-05-18T14:46:57.373 に答える
0

別の方法として、ステータスが目的のモードにあるかどうかをオブジェクトにチェックさせることもできます。

そうでない場合、オブジェクトのメソッドは例外をスローできます。

テストされていない例:

class Klasse
{
    const WANTED_VALUE    =  1;
    const UNWANTED_VALUE  =  2;

    private static $constant_names  =  array();
    p... function __construct ()
    {
        if ( empty( self::$constant_names ) )
        {
            $class            =  new ReflectionClass( __CLASS__ );
            $constants        =  $class->getConstants();
            $constants        =  array_flip( $constants );// requires the constant's values to be unique
            self::$constants  =  $constants;
        }
    }
    public function checkNeededStatus ()
    {
        $needed_status  =  self::WANTED_VALUE;// could also be a parameter(an argument) with a default value
        if ( $this->status !== $needed_status )
        {
            $constant_name  =  self::$constants[ $this->status ];
            $message        =  'Status is wrong, '
                . 'should not be: `' . $constant_name . '`.'
            ;
            //$message .=  '(it should be `' . self::$constants[ $needed_status ] . '`)';
            throw new Exception( $message );
        }
    }
}

$objInstance  =  new Klasse();
$objInstance->method1();
$objInstance->method2();
$objInstance->checkNeededStatus();

クレジット :

Reflection を使用しないことを検討した方がよいかもしれません。スローされたメッセージはクラス内にとどまるため、メンテナンス性をあまり損なうことなく実行できる可能性が高くなりました。

于 2010-10-26T14:43:07.307 に答える