In PHP I can wanting to eval a string, which might call one of my user defined methods.
What I have is something like:
function convertToBytes($value)
{
$number=substr($value,0,-1);
switch(strtoupper(substr($value,-1))){
case "K":
return $number*1024;
case "M":
return $number*pow(1024,2);
case "G":
return $number*pow(1024,3);
case "T":
return $number*pow(1024,4);
case "P":
return $number*pow(1024,5);
default:
return $value;
}
}
$expression = 'if (convertToBytes("1024K") >= 102400)
return true;
else
return false;';
$value = eval($expression);
I am wondering if I can do that without the use of an eval.
I'm confused. You shouldn't ever have to use eval()
for something like this, when you can easily set $value
to the real boolean value such as:
$value = (convertToBytes("1024K") >= 102400);
Your best bet it splitting it up. So that it is infact something like this:
function convertToBytes($value, $type) {
...
}
so then you can do:
$value = (convertToBytes(1024, 'K') >= 102400);
Yourfunction would look like:
function convertToBytes($value, $type = "K")
{
switch($type){
case "K":
return $value*1024;
case "M":
return $value*pow(1024,2);
case "G":
return $value*pow(1024,3);
case "T":
return $value*pow(1024,4);
case "P":
return $value*pow(1024,5);
default:
return $value;
}
}