I've heard this term used with scripting languages such as PHP. What exactly does it mean?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
Dynamic typing is a definitive characteristic of a language. A short explanation might be:
For example, in PHP you can write
and then go on to say
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
and2
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
the compiler will not attempt to see if
$object
is of a type that has a method namedquack
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).