PHP Manual Masterpieces

RSS
Oct 6

Here’s my int, so cast it maybe

From a comment on the documentation of variables:

function CAST_TO_INT($var, $min = FALSE, $max = FALSE)
{
    $var = is_int($var) ? $var : (int)(is_scalar($var) ? $var : 0);
    if ($min !== FALSE && $var < $min)
        return $min;
    elseif($max !== FALSE && $var > $max)
        return $max;
    return $var;
        
}

I am truly struggling to imagine what the point of this “utility” function is. It “casts to int” by… using the built-in means of casting to int. If PHP can’t figure how to make an int out of what you handed it, it gives you a zero, as this goes out of its way to do explicitly.

So that just leaves these mysterious min/max clamping parameters, which have nothing to do with casting. This function should have been named CLAMP_INT_TO_RANGE. Note, however, that $min and $max do not have to be integers! That means that the call CAST_TO_INT(6, "foo", "bar"); will return “bar”. Casting to int, except when suddenly string.

(Comparing an int to a string will cast the string to an int by the normal rules, meaning both “foo” and “bar” are 0 for the purposes of comparison against 6 as they do not represent an ASCII-encoded integer. That is, when you’re using “==” and not “===”. As a young programmer I completely failed to understand what the distinction there is.)