开发者

php forcing type

开发者 https://www.devze.com 2023-01-14 17:43 出处:网络
I have a collegue who constantly assigns variable and forces th开发者_Go百科eir type.For example he would declare something like so:

I have a collegue who constantly assigns variable and forces th开发者_Go百科eir 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?


There are a few benefits.

  1. Type-checking. Without type-checking, 0 == false and 1 == true.
  2. Sanitizing. If you're inserting the value into an SQL query, you can't have SQL injection because string values are converted to zero.
  3. Integrity. It prevents inserting invalid database data. Again, it converts to zero, so you won't be trying to insert a string into a integer field in a database.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消