2

Following my other question, is there a general rule of thumb, when we should pass a setting-like value, that controls class' behavior (for example displayed texts) as as class' constant or variable, one-by-one, and when it is better to "pack" them to one associative array? Or is it just a choice of the developer?

For example -- is this approach better (PHP code):

class SomeClass
{
    public $errorIncorrectProtocol = 'Please, don't use GET protocol in this context!';
    public $errorMissingId = 'The ID can't be empty or equal zero...';
}

than this one:

class SomeClass
{
    public $errorMessages = array
    (
        'IncorrectProtocol'=>'Please, don't use GET protocol in this context!',
        'MissingId'=>'The ID can't be empty or equal zero...'
    );
}

and if yes -- then, why?

2

A good practice here (in PHP at least) is to use a combination of constants and arrays. To follow your error messages example:

class SomeClass {
    const ERR_INCORRECT_PROTOCOL = "incorrectProtocol";
    const ERR_MISSING_ID = "missingId";

    public $errorMessages = array(
        self::ERR_INCORRECT_PROTOCOL => "Please, don't use GET protocol in this context!",
        self::ERR_MISSING_ID => "The ID can't be empty or equal zero..."
    );
}

Error messages can then easily be retrieved:

$someObj = new SomeClass();
$someObj->errorMessages[SomeClass::ERR_INCORRECT_PROTOCOL];

Generally speaking, I don't think having individual variables in this context provides any benefits over using a constants and arrays. Instead, it simply clutters the internals of your class, or worse (if they're publicly exposed) clutters your API and possibly confuses developers (what's this errorMissingId? Is it some error object? A string? Is it safe to change? Do I need it?)

|improve this answer|||||
  • Thanks for a great answer. Do you have any source of this "good practice"? I can't understand, how using extra constants for keys in assoc. array could benefit code or me? – trejder Feb 24 '14 at 13:06
  • I've never seen it written down, but I use it myself and I've seen it used in a number of large PHP projects too. – Andy Hunt Feb 24 '14 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.