I don’t think this question has been asked before (at least I couldn’t find it if it has…)
Recently I’ve started to work on a bigger project (at least more OOP(…by which I mean functions, classes, and objects)) than I usually use; However what variable type my function arguments should be is driving me crazy, for example:
<?php
function uberFunc($myArgument){
switch($myArgument){
//Stuff
}
}
?>
And lets say, in this example, that $myArgument can only be a certain number of responses (ie it is not user created). For example, $myArgument might define how sql is ordered or which hash to use or some predefined list of values. Then the case statement turns $myArgument into some action (appending a mysql string or hashing a string a certain way).
tl;dr: Have argument for function that can only be one of a set of predefined values.
My question is: for these types of variables is it better to use a string literal (which will be decoded by a switch-case statement) or numbers (which would also be decoded by a switch-case statement)?
Currently I have been flip-flopping which is starting to create awkward code, so I want to chose one (string literals or numbers) and stick with it
Advantages (that I know of) to using string literals:
- Readability
- Direct insertation (ie, if your passing on a variable which determines how to organize your sql, you can do something like
"SELECT * FROM main ORDER BY ".$myArgument
Advantages (that I know of) to using numbers:
- Can be manipulated by math (if you ever need such a piece of code)
- I believe they process marginally faster (not enough to make a difference though)
Actually, the only thing that I actually see that could be right is “readability”.
About whether or not the variables can be “directly inserted” into your sql database, if you have
"SELECT * FROM main ORDER BY ".$myArgumentThis will work whether or not $myArgument is a string or an integer. However, you should be using prepared statements (e.g. with PDO) which will prevent SQL injection as well as other advantages.
Can be manipulated by math?
PHP will convert quoted strings to their numeric values when doing mathematical operations.
As the other person said, the difference in speed is quite marginal.
Sure, it’s twice as long, but 0.1 seconds difference for 1 million iterations is nothing. Basically doing the first is stupid if you can do the second, however if it increases readability, as you can tell, it’s really not going to make much of a difference in speed.