| > Can you explain why? Hopefully. > How does putting (int) before the arguments to function help anything? It wouldn't. Anyone who is casting from an unknown type to an int by using just `(int)` is doing something wrong in my opinion. Even in web-based applications there are at least two layers of code:
i) One where the type of the values are unknown and they are represented as strings.
ii) One where the types of the values are known. At the boundary between these two layers you should have code that inspects the strings that represent the input values, check that they are acceptable, and convert them to the desired type. If the input values cannot be converted to the desired type, the code needs to give an error that is both specific to the type of error so that a computer can understand it, as well as provide a human understandable explanation of why the conversion was not allowed. The reason why I want strong types is that I never, ever want to blindly cast from one type to another. The decision about how to convert from one type to another, should always be made at a boundary between areas of the application where types are known, and the areas where the types are unknown. I always want to be forced to make that decision in the right place, using code that gives useful errors and messages, rather than having the value coerced into the desired type. tl;dr I won't use (int) to cast, I will use something like the code below. cheers
Dan function validateOrderAmount($value) : int {
$count = preg_match("/[^0-9]*/", $value);
if ($count) {
throw new InvalidOrderAmount("Order amount must contain only digits.");
}
$value = intval($value);
if ($value < 1) {
throw new InvalidOrderAmount("Order amount must be one or more.");
}
if ($value >= MAX_ORDER_AMOUNT) {
throw new InvalidOrderAmount("You can only order ".MAX_ORDER_AMOUNT." at a time.");
}
return $value;
}
function processOrderRequest() {
$orderAmount = validateOrderAmount($_REQUEST['orderAmount']);
//Yay, our IDE/static code analyzer can tell that $amount is an int if the code reached here.
placeOrder($orderAmount);
}
|
So from your code it looks like the only benefit of strict mode is in case you forget to do the validation/conversion it will warn you? I guess that's reasonable. Is there any other benefit?
To me it seems that Ze'ev's proposal would be even better for you - it does the equivalent of the validation and conversion automatically including with an error if it doesn't validate.
You wrote "let's ignore that", but it really seems like to best of all worlds to me. Any idea why it was rejected so badly? Is it because the coercion rules are different from the rest of PHP?