Reputation: 59
I have a collegue who constantly assigns variable and forces their type. For example he would declare something like so:
$this->id = (int)$this->getId();
or when returning he will always return values as such:
return (int)$id;
I understand that php is a loosely typed language and so i am not asking what the casting is doing. I am really wondering what the benefits are of doing this - if any - or if he is just wasting time and effort in doing this?
Upvotes: 3
Views: 165
Reputation: 21388
To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.
http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.
http://www.php.net/manual/en/language.types.type-juggling.php
You can do something like this instead.
function hello($foo, $bar) {
assert(is_int($foo));
assert(is_int($bar));
}
http://php.net/manual/en/function.assert.php
Upvotes: 1
Reputation: 12217
There are a few benefits.
Upvotes: 4