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?

asked Feb 24, 2014 at 12:18

1 Answer 1

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

answered Feb 24, 2014 at 12:29
2
  • 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? Commented Feb 24, 2014 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. Commented Feb 24, 2014 at 13:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.