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
  • When PHP sees an undefined constant like CONSTANT_VALUE, it treats the constant as the string 'CONSTANT_VALUE' Commented May 15, 2009 at 19:57

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
0

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

2 Comments

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

Your Answer

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.