|
Thought I'd write a small tutorial, so here goes. In php you can have variables, which you can in pretty much every language, and you can have constants, a form of variable with it's own properties, which I'll list now: - A constant once defined, cannot be changed or undefined
- A constant must start with a letter (a-z) or an underscore, it may contain numbers too though, just not at the beginning.
- Constants may only contain scalar data (boolean, int, string and float)
- A constant doesn't comply with the variable-scope.
The last point there is pretty much why constants are good (and why they are called constants really). You can access the value of a constant (or check if it's defined) -anywhere- in your software, it could be a function, an oop wrapper, a function inside an oop wrapper, anywhere. So, how do we define constants? It's really easy, take a look: define('CONS_NAME', 'CONS_VALUE'); How can you get the value? Simply by calling it's name, for example: echo CONS_NAME; Or you can use constant();, more info on that here: uk.php.net/manual/en/function.constant.phpSo how about checking if the constant exists? if (defined('CONS_NAME')) { echo 'constant is defined'; } That's all easy then, what about a good scenario for a constant, well, let's say your software all ran through 1 file, index.php for instance, index.php however included/required other files, say functions.php and such, all good, but what if you didn't want users to access functions.php via there browser? Simple. In index.php you'd place: define('IN_SYS', true); At the top (below <?php/<?) of functions.php if(!defined('IN_SYS')) { die('<h4>You may not access this script directly.</h4>'); } Well, I'm sure you can put it to use as you see fit, hope this helped - Zero Tolerance
|
|
|
|
|
you have some examples of what you can use constants in?
|
|
|
|
|
I think its just a way to keep more organized.
See, you could have only text data stored in it, so basically, you could set a constant for the membres access levels (Admin, EMod, Mod, Member, Guest, etc.) and you could save the variables for arrays, MySQL connections, etc.
|
|
|
|
|
Well it can store text/numbers/float numbers and boolean (true/false). Personally i'd use constants for the example I gave and any variable that didn't need to be changed that would be used globally throughout a program, another example would be vBulletin storing the database prefix in a constant, it's used all over so it makes sense to make it a constant - Zero Tolerance
|
|
|
|
|
Can you redefine a constant at any time?
|
|
|
|
|
|
Oops. I missed that while I was reading over it.
|
|
|
|