开发者

PHP: are switch-case statements with strings inefficient?

开发者 https://www.devze.com 2023-02-24 04:58 出处:网络
In my PHP layer I\'m receiving error codes as strings (\"NOT_FOUND\", \"EXPIRED\", etc). It\'s a small list of possible strings, perhaps 开发者_StackOverflowa dozen.

In my PHP layer I'm receiving error codes as strings ("NOT_FOUND", "EXPIRED", etc). It's a small list of possible strings, perhaps 开发者_StackOverflowa dozen.

What's the most efficient way of dealing with these? Using switch-case against string constants stored in a class, or should I parse them to numbers (or something) first? Or is PHP smart enough so it doesn't really matter?


You might want to consider using constants? Let's say you have a class Error and define all error codes there like this:

class Error {
   const NOT_FOUND = 0;
   const EXPIRED = 1;
   // and so forth
}

And then you can use them in your code by accessing them like Error::NOT_FOUND and a switch statement wouldn't need to compare strings but has plain ints without downgrading readability.


It really depends on what you want to do with the strings. Do you want to output error messages? Then instead of a case statement you could use a lookup table like this:

$messages = array(
  'NOT_FOUND' => 'The file was not found',
  'EXPIRED' => 'The cookie expired'
  // ETC
);
echo empty($messages[$error]) ? "Unknown error" : $messages[$error];

With PHP 5.3 you could also store code in the array to handle the error situations:

$handlers = array(
  'NOT_FOUND' => function() { /* Error handling code here */ },
  'EXPIRED' => function() { /* Other error handling code */ }
 );
 if(!empty($handlers[$error])) { 
   $handler = $handlers[$error];
   $handler();
 }
 else {
   echo "Could not handle error!"; die();
 }

With a technique like this you avoid case statements that go over several pages.

With PHP < 5.3 you might look into call_user_func for dynamic dispatching of error handling functions.


Strings can't be recognised as class constants. But the answer on your question is that it doesnt really matter if you do it like this:

switch (className::{$errorCode}) { // $errorCode == name of the constant, like NOT_FOUND
// Cases here.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号