To register for an Internet.com membership to receive newsletters and white papers, use the Register button ABOVE.
To participate in the message forums BELOW, click here
What is the best way to have a config consisting of a set of variables and error messages set in a class?
At the moment I have it at the top of each method that uses it. Some people may say that is bad practice, but I'm trying to see about another solution.
I was thinking about a class like:
PHP Code:
class config {
function __construct(){
const var = "asdf";
const var2 = 2;
}
}
Not even sure the construct is needed ..and usage i would do something like config::var, but my variable formats are in the array types at the moment ($err['err_type'] = "error message";).. so is there anyway to preserve that format in a class, not sure if a constant can be assign as an array hehe.
class Config
{
static private $errors = array(
'err1' => "Error 1",
'err2' => "Error 2",
);
static public function getError($key)
{
return self::$errors[$key];
}
}
Config::getError("err1");
Another common way to handle error messages is to put them in a bunch of regular constants in a file, and include them at the top of each script. They will be visible in every context.
You could, by changing the access type of the array to public. But having a get method is better practice, member variables should really only be accessed within a class.
Out of interest, I would probably opt for either the 2nd method, or for putting the errors in a database, depending on how much content management is needed.
So it would look something like this?:
public $err['err_type'] = "error message";
Although I get the error:
Code:
Parse error: syntax error, unexpected '[', expecting ',' or ';'
The one you prefered (the defines), you can't really organise them with arraytypes, sure ya can't? e.g. define("err2['error_name']", "Error 2"); | Using: Config::err2['error_name']
Going to use that first method you gave and will keep the getmethod as well (as you say, it is good practice too!).
There isn't any performance drawbacks for this config setup or anything?
Edit: but then the config::$error['err_name'] looks more like a variable than the other (better readablity)... hehe I'm stuck again in which to choose.
You can't set member variables dynamically (i.e. by using $_SERVER in the definition.). This is the case in PHP 4 + 5. You would have to do it in a class method, or use a literal string.
You can't use a variable (i.e. in your case $_SERVER['HTTP_HOST']) inside of the array definition. Only string literals (i.e. 'www.mysite.com' or something)