Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 2 down vote accepted

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();

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?)

share|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. – AndyBursh Feb 24 '14 at 13:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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