Using arrays as constants in PHP by Bunkermaster
- 9 January, 2011 -
- PHP Coding -
- Tags : array, constant, constants, PHP, readability
- 0 Comments
Sometimes, I find myself facing a language limitation that baffles me.
Generally speaking I never hard code any setting in my code. I extract it all into my precious config file (or my config table, material for another post) so that I can change the inner workings of my code. Sometimes those settings come in the form of strings, integers and even arrays of the previously mentioned.
To define an array as a constant you can’t just define an array as the constant. For some reason PHP doesn’t allow that.
<?php define( 'A_CONSTANT_ARRAY' , array( 'ONE' => 'ONE' , 'TWO' => 'TWO', 'THREE' => 3)); // won't work ?>
So you have to use the serialize function instead. It’s a simple bypass really since you actually define a string as a constant. That string happens to be a serialized array.
<?php define( 'A_CONSTANT_ARRAY' , serialize( array( 'ONE' => 'ONE' , 'TWO' => 'TWO', 'THREE' => 3))); // will work ?>
To use it it’s a simple matter of unserializing the string into a regular array and you can access its values. Now a few questions arises:
Q: what’s the point of using a constant to assign it to a variable later on?
The constant is accessible anywhere in your code. No matter how deep you are in your code, you can always access it.
Q: How do I access the content of my array?
Simply unserialize the constant string into a variable.
<?php define( 'A_CONSTANT_ARRAY' , serialize( array( 'ONE' => 'ONE' , 'TWO' => 'TWO', 'THREE' => 3))); $some_variable = unserialize( A_CONSTANT_ARRAY ); var_dump( $some_variable ); ?>
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.