Part of a series on why PHP’s type system is the best in the world. This post explores a class of bugs frequently seen in other dynamically typed languages, which doesn’t happen in PHP.
What Bugs Are We Talking About?
- 2+2 = 4
- “hello” + 2 = “hello2”
- “2”+2 = “22”
It’s easy to see how the third case in particular could cause bugs.
Here is a handy table, to show what happens if you try to add two and two in various languages, where the left-hand operand is presented as a string:
We need dynamic typing in web languages because the internet is made of string. Pretty much everything that enters your application from HTTP POST data, cookies or query strings is a string. It is often necessary to treat input as being of a different type later. PHP’s type system is best suited for this, because it has implicit typecasting and coercive typehinting, but does not use type-dependent operator overloading.