Does PHP have structs or enums and if not what is the best implementation for them?
This question already has an answer here:
I actually created my own kind of enum for PHP and it works just fine for what i need to do. no typedefs but its nice :D
Function enum($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
}
Usage (EXAMPLE):
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)
}
Nope.
You'll have to go with arrays or, if you require something that has a custom type, classes and objects.
你可以用常量做类似的事情,但它与专用枚举不同。
链接地址: http://www.djcxy.com/p/28918.html上一篇: 使用正则表达式从url中提取参数值