Using Constants

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Using Constants

Post by Ree »

Is it ok to use constants in many of my written classes? Since constants are global, including a file with a bunch of define()'s in the main script makes them available to all objects used in that script. Those aren't any special data or anything, just language strings (translated user-end messages/errors etc). It's very convenient for me this way, I can simply use eg

Code: Select all

$this->error = LANG_548;
in some class and be fine with it. But is it an ok way to do it? What if the file get's larger? Say, a few hundred define()'s? Could there be any performance issues?
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

I'd tend to see error messages as belonging to the class which identified the error state, or perhaps to a client which received a false value when it requested something from another object - hence they'd be class properties.

For multi-language errors, you could maybe return an id and then look up a phrasebook - a simple container defining a bunch of strings.

It's often useful to customise an error using sprintf to add some details, eg:

Code: Select all

class Foo
{
    var $_error = 'Could not find item [%s].';

    // etc
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I feel it's generally a good idea since you are abstracting out output language specific data among other things..
Post Reply