PHP是否有结构或枚举,如果不是什么是他们最好的实现?
这个问题在这里已经有了答案:
我实际上为PHP创建了自己的枚举类型,对于我需要做的事情,它工作得很好。 没有typedefs但很好:D
函数枚举($ array,$ asBitwise = false)
/*
* I formed another version that includes typedefs
* but seeing how this hacky is not viewed as compliant
* with programming standards I won't post it unless someone
* wishes to request. I use this a lot to save me the hassle of manually
* defining bitwise constants, but if you feel it is too pointless
* for you I can understand. Not trying to reinvent the wheel here
*
*/
function enum($array, $asBitwise = false) {
if(!is_array($array) or count($array) < 1) return false; // Error incorrect type
$n = 0; // Counter variable
foreach($array as $i) {
if($i === null) {
if($n == 0) {
if(!define($i, 0)) return false;
} else
if(!define($i, $asBitwise ? 1 << ($n - 1) : $n)) return false;
} $n++;
} return true; // Successfully defined all variables
}
用法(示例):
enum(array(
'BrowserTypeUnknown', // 0
'BrowserTypeIE', // 1
'BrowserTypeNetscape', // 2
'BrowserTypeOpera', // 3
'BrowserTypeSafari', // 4
'BrowserTypeFirefox', // 5
'BrowserTypeChrome', // 6
)); // BrowserType as Increment
$browser_type = BrowserTypeChrome;
if($browser_type == BrowserTypeOpera) {
// Make Opera Adjustments (will not execute)
} else
if($browser_type == BrowserTypeChrome) {
// Make Chrome Adjustments (will execute)
}
enum(array(
'SearchTypeUnknown', // 0
'SearchTypeMostRecent', // 1 << 0
'SearchTypePastWeek', // 1 << 1
'SearchTypePastMonth', // 1 << 2
'SearchTypeUnanswered', // 1 << 3
'SearchTypeMostViews', // 1 << 4
'SearchTypeMostActive', // 1 << 5
), true); // SearchType as BitWise
$search_type = SearchTypeMostRecent + SearchTypeMostActive;
if($search_type & SearchTypeMostRecent) {
// Search most recent files (will execute)
}
if($search_type & SearchTypePastWeek) {
// Search files from the past will (will not execute)
}
if($search_type & SearchTypeMostActive) {
// Search most active files AS WELL (will execute as well)
}
不。
你将不得不使用数组,或者,如果你需要一些具有自定义类型,类和对象的东西。
你可以用常量做类似的事情,但它与专用枚举不同。
链接地址: http://www.djcxy.com/p/28917.html上一篇: Does PHP have structs or enums and if not what is the best implementation for them?
下一篇: How to get a youtube playlist using javascript API and json