Php boost type

I have a colleague who constantly assigns a variable and forces them to type. For example, it will declare something like this:

$this->id = (int)$this->getId();

or when returning, it will always return values ​​as such:

return (int)$id;

I understand that php is a freely typed language, so I don't ask what casting does. I am really curious what benefits do this - if any - or if he just spends time and energy on it?

+3
source share
2 answers

There are several advantages.

  • Type check . Without type checking, 0 == false and 1 == true.
  • Disinfection . If you insert a value in an SQL query, you cannot have SQL injection because string values ​​are converted to zero.
  • . . , , .
+4

integer, (int), ( ). , , , . intval() .

http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting

PHP ( ) ; , . , $var, $var . $var, .

PHP - '+'. , , . , . ; , .

http://www.php.net/manual/en/language.types.type-juggling.php

- .

function hello($foo, $bar) {
    assert(is_int($foo));
    assert(is_int($bar));
}

http://php.net/manual/en/function.assert.php

+1
source

Source: https://habr.com/ru/post/1763336/


All Articles