I'm wondering about where to define some constants. I'm leaning toward defining these constants as class constants (i.e., MyClass::CONSTANT_NAME). However, more than one class is going to need to refer to these constants. If I refer to MyClass::CONSTANT_X in some other class then encapsulation gets broken. Come to think of it, if I refer to a constant at all in some class then encapsulation is kind of broken anyway and I'll also have to define a new file which defines my constants which live in the global namespace.
Can anyone provide some general heuristic guidance about where and when to define constants vs. class constants and how to best preserve encapsulation?
The context where this pops up is a PHP gateway for remote procedure calls (RPCs). Part of what I need to do is serialize and unserialize RPC requests. I would like to let users specify a method for serializing and unserializing RPCs when they instantiate a service object in the client software. A single Server class can support multiple Service objects In other words, a given client might use JSON serialization or XML encoding for requests depending on the context. The serialization method is specified when one instantiates the Service class:
$myService = new Service('rpcGateway.php', 'JSON');
$myOtherService = new Service('rpcGateway.php', 'XML');
but rather than specifying a string, I would like to let users use a constant because the compiler will complain about a mistyped constant whereas a mistyped string will go right thru. Further complicating matters is the fact that I would like both the Service class and the Server class to share the constant definitions.
I hope that's not too wordy or confusing. Any advice and/or discussion would be much appreciated.