What to define Predefined Constants as

2019-02-26 18:12发布

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?

2条回答
男人必须洒脱
2楼-- · 2019-02-26 18:30

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-26 18:39

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.

查看更多
登录 后发表回答