Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jul 2005
    Posts
    342
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question How to Emulate Enum in PHP like C?

    Hi,
    In C language, there is enum, and I can do the following:

    Code:
    enum {
      DOG,
      CAT,
      BIRD,
      MAX_NUM_OF_ANIMALS
    };
    There is no enum in php, how can I emulate enum in php? I want to do better than just use define() because I need to put use numbers like this "define(DOG, 0); define(CAT, 1);" and there is no way to access MAX_NUM_OF_ANIMALS without doing another define.

    Many thanks.

  • #2
    Senior Coder nikkiH's Avatar
    Join Date
    Jun 2005
    Location
    Near Chicago, IL, USA
    Posts
    1,973
    Thanks
    1
    Thanked 32 Times in 31 Posts
    Use an associative array.
    http://www.hypermedic.com/php/arrays3.htm

    C doesn't let you refer to array index as a string. PHP (among others) does.

    If that doesn't suit you, you can make an enum class yourself...

    If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
    Bored? Visit
    http://www.kaelisspace.com/


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •