1

I have lists where strings correspond with values. For example, in a company list I could have Microsoft correspond with the letters MS.

Obviously, this could be transposed as a table in MySQL to make the list extensible but, from curiosity, how would you express this in constant form in PHP ?

P.S: There is the class-with-constants approach (see accepted answer here: PHP and Enumerations) to act as an enumeration but would that really be of any use seeing that enumerations map to integer values ?

Community
  • 1
  • 1
James P.
  • 19,313
  • 27
  • 97
  • 155

3 Answers3

4

How about using define

define("MS","Microsoft");
echo MS;

This would echo Microsoft.

http://php.net/manual/en/function.define.php

Also the link you gave to a possible solution could just as easily be used with strings instead. The only reason it acts as an enum from other languages is because you define the values from 0 to n, instead of doing that just use string instead.

class Companies {
    const MS  = 'Microsoft';
    const IBM = 'International Business Machines';
}

echo Companies::MS;

I think this would work.

Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
  • Hadn't thought of define. Thanks for the mention. The following is related: http://stackoverflow.com/questions/5892226/php-define-constant-inside-a-class – James P. Jun 27 '12 at 09:04
  • 1
    Saw your edit. The following could be used to reproduce enum-like behaviour. http://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class – James P. Jun 27 '12 at 09:11
1

i would probably start by looking at multi dimentional arrays if a single company can have many corresponding letters, however the draw back being that they can get difficult to manage, your other option is to define constants

Nicholas King
  • 938
  • 7
  • 22
1

If you have key-value pairs you can put those into an object, so its more practical to use.

check on this link: the arrayToObject() function

PazsitZ
  • 131
  • 2