I'm guessing its better to just use a protected variable in the class and use a getter to get the value from the class. Am I correct?
You can have class constants in PHP 5.
Is it ok to call a Constant that was done via define() outside of the class?
example
<?php define(MYCONSTANT, ....)
class myclass { MYCONSTANT... } ?>
Or is that bad practice? I've seen it done before so just curious.
You can tell them apart because the class constant will be prepended with a class name. But I don't see what advantage there would be in having two different constants with the same name (or one constant declared twice).
I've commented on which one to use in the past.
You could also consider defining the application-level constants in an interface, then use that interface in any class that needs them.
<?php interface Constants { const FOO = 'bar'; } class Test implements Constants { public function foo() { echo self::FOO; } } $test = new Test(); $test->foo();
The problem I read is that class constants wont let you do complicated things to set the constant. I have a lot of constants that have to run through a function or need to be strung together via concatenation. For example:
interface Constants { const CONST_REMOTE_ADDR = $this->preg_replace('/[^0-9\.]/', '', $_SERVER['REMOTE_ADDR']));//ip address const CONST_CONCATINATION = 'whatever' . 'something' . $this->test('whatever'); }
That holds true for define()'d constants too: the value assigned must be scalar (or null), it cannot be a function call. If you need to define a value to include a result of a function call, then it will have to be a variable, not a constant. (Or I suppose you could assign the result of a function to a variable and then assign that variable to a constant, but that seems both unnecessary and, strictly speaking, not really a "constant". Perhaps you could look into the "registry pattern" for a class to hold application-wide variables?