dongwen2794
dongwen2794
2012-03-22 19:17

PHP类常量数组转换

  • enums
  • php
  • casting
  • arrays

To simulate enums in PHP I like to use class constants.

e.g.

class FRUIT
{
    const apple = 1;
    const orange = 2;
    const lemon = 3;
    const pear = 4;
};

I have a case where I'd like cast this class to an array to populate a select list. However because class constants behave statically casting does not work e.g. (array)(new FRUIT()); nor does the get_object_vars() method.

What's the best way to get round this? Do I need to create an internal function to iterate the constants and return an array?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答