views:

141

answers:

2

I have a database class that automatically sets up a connection to the database and does some basic input filtering and whatnot. I am looking at setting some predefined constants to adjust the behavior of the class methods. What should I set the values of the constants as? Since the values will never be referred to, or compared, directly but only in the context of the constant name does the value even matter?

One strategy I have come across is setting a constant to a bit value so that bitwise operators can be used to combine constants. In this case it doesn't look like that functionality will be necessary, but you never know.

Often I get messages like

Notice: Use of undefined constant CONSTANT_VALUE - assumed 'CONSTANT_VALUE'

Is this treating the constant like the string 'CONSTANT_VALUE' or the constant CONSTANT_VALUE? Should I be defining the value of my constants as strings of the same name to compensate for this? This occurs when I am using constants I know are defined at some point, like DOCUMENT_ROOT.

Am I missing a better practice that either of these?

+1  A: 

If you are getting that message, the constant in question is not defined at the point where that code is running, and it is being treated as the string 'CONSTANT_VALUE'.

If the values of a set of constants that you're defining are completely arbitrary and do not need to be bitmaskable, use the sequence of positive integers.

chaos
what about the example of $_SERVER[DOCUMENT_ROOT]? I assume that is a defined value, but I get the notice and it does work. Is DOCUMENT_ROOT an actual defined constant?
tvanover
Mmm no. It's $_SERVER['DOCUMENT_ROOT']. DOCUMENT_ROOT is not a constant at all. The only reason it's working when you do $_SERVER[DOCUMENT_ROOT] is because of the failover to a string value that it's telling you about in that warning. The failover is an attempt to compensate for incompetent coding, not a supported language feature, which is why it issues a warning.
chaos
A: 

If the constants are not going to be used outside the database class you don't need to define global constants, you can use class constants:

http://uk.php.net/manual/en/language.oop5.constants.php

palako
well they will be used by other scripts calling database functions. ie $database->action($values, CONSTANT_VALUE). Would class functions be callable like $database->action($values, DbClass::CONSTANT_VALUE)?
tvanover
yep. Check out the manual here: http://uk2.php.net/manual/en/language.oop5.constants.php
palako