Skip to main content
added 821 characters in body
Source Link
Javier
  • 9.9k
  • 1
  • 29
  • 35

You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept. That means, variables don't have a type, values do.

A 'type casting' is an expression that produces a new value of a different type of the original; it doesn't do anything to the variable (if one is involved).

The one situation where I regularly type cast values is on numeric SQL parameters. You're supposed to sanitize/escape any input value you insert into SQL statements, or (much better) use parameterized queries. But, if you want some value that MUST be an integer, it's much easier to just cast it.

Consider:

function get_by_id ($id) {
   $id = (int)$id;
   $q = "SELECT * FROM table WHERE id=$id LIMIT 1";
   ........
}

if I left out the first line, $id would be an easy vector for SQL injection. The cast makes sure that it's a harmless integer; any attempt to insert some SQL would simply result in a query for id=0

You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept. That means, variables don't have a type, values do.

You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept. That means, variables don't have a type, values do.

A 'type casting' is an expression that produces a new value of a different type of the original; it doesn't do anything to the variable (if one is involved).

The one situation where I regularly type cast values is on numeric SQL parameters. You're supposed to sanitize/escape any input value you insert into SQL statements, or (much better) use parameterized queries. But, if you want some value that MUST be an integer, it's much easier to just cast it.

Consider:

function get_by_id ($id) {
   $id = (int)$id;
   $q = "SELECT * FROM table WHERE id=$id LIMIT 1";
   ........
}

if I left out the first line, $id would be an easy vector for SQL injection. The cast makes sure that it's a harmless integer; any attempt to insert some SQL would simply result in a query for id=0

Source Link
Javier
  • 9.9k
  • 1
  • 29
  • 35

You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept. That means, variables don't have a type, values do.