PHP’s Type System, part I: Dynamic Typing Causes Bugs

By | 2020-11-04

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?

The issue in question is caused by a feature of some languages, including Python and Javascript, but not PHP. ‘Bugs caused by dynamic typing’ are actually caused by type-dependent operator overloading. This affects Javascript and Python, for example, but not PHP, as PHP doesn’t do type-dependent operator overloading.

Principally, the operator in question is the ‘+’ symbol. In Javascript, the ‘+’ symbol can be used as an arithmetic operator (plus), or as a string operator (concatenation). Here is what the ‘+’ symbol does in Javascript, for example:

  • 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:

A table showing what happens when you add two plus two in various langauges. Python and Javascript, Java and PHP are in the list. Only PHP returns '4'.
Table showing what happens if you try to add two plus two in various languages. The left-hand operand is a string. Only in PHP is the result 4.


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.