What is Dynamic Typing?

dikidera picture dikidera · Sep 13, 2011 · Viewed 10k times · Source

I've heard this term used with scripting languages such as PHP. What exactly does it mean?

Answer

Jon picture Jon · Sep 13, 2011

Dynamic typing is a definitive characteristic of a language. A short explanation might be:

A language has dynamic typing when it does not associate values strictly with a specific type, but it is designed to "decide" what the type of a value should be at runtime, based on how you are attempting to use it.

For example, in PHP you can write

$count = "5"; // defines a string variable

and then go on to say

$count = $count * 2; // this is legal and has the obvious result¹

What happened here? For one, the compiler did not complain that you are attempting to multiply a string by a number and refuse to compile the program (such as would happen in languages like C, C++, C# and Java). It produced code to forward the arguments $count and 2 to the multiplication operator just like you asked and moved on.

With the program now compiled, dynamic typing comes into effect at runtime. When the multiplication operator gets around to look at its operands, it checks to see what is the current, if you will, type of each one. As before, it's a string and an int. But the operator knows that it can only multiply two integers (let's ignore floats for simplicity), so it has to somehow produce an integer value from the string. All dynamically typed languages have rules that stipulate how such a conversion works between all pairs of value types; in this case, PHP produces the integer 5 from the string "5".

Another aspect of dynamic typing you might come across is called duck typing; this only applies to values of class types (i.e. not primitives). In short, duck typing stipulates that when you write

$object->quack();

the compiler will not attempt to see if $object is of a type that has a method named quack that takes no arguments. Rather, it will attempt at runtime to see if $object actually has such a method; if it does, the method will be called regardless of what type of object we have at hand (might be a duck, might be a dog for all the compiler cares).

Footnotes:

¹ Multiplying a string by an integer is what dynamic typing is all about (producing an integer from a string because the multiplication demands one); however, there is also loose typing at work here (allowing the multiplication to compile without being able to prove that both operands are actually ints).