|
home—lects—hws
D2L—breeze (snow day)
There are some things that are not an error, but should be.
For example:
This means that if you ever mis-type a variable name,
you won't get an error, but instead PHP will happily
proceed as if nothing is wrong1.
PHP does not have your back.
Solution:
Fortunately, people figured out that PHP's default behavior
is unforgiveable, and added a switch to turn the above
three behaviours into errors, as they should be:
PHP is dynamically typed: that is, it figures out the type of values at run time — whether an expression evaluates to a boolean, int, float, string, arrays, objects. (Compare that to Java, which is statically typed: it knows the type of each value at compile-time, since the programmer is required to state the type each variable will hold, and the type returned by a function, and the type that must be passed in to each function.) So a PHP variable can hold an int at one moment in time, and later hold a string; a function might return a string sometimes and return a boolean other times, etc.. Javascript, python, and racket are other untyped languages.
Some people say that PHP is untyped; that is wrong. It is always aware of the type of any value. PHP has the types you might expect, including boolean, int, float, string, arrays, objects. (It does not have single characters, just strings-of-length-one. It makes one wonder: what is a string made out of? What is being strung together?) But one thing that gives people the impression there aren't types is because PHP is particularly fast-and-loose about type conversions — “type juggling” — much more than other languages.
Conversion between strings and integers:
echo "hello" + "world"; echo 12 + 3; echo "12" + "3"; echo "12" + 3; echo "12hello" + "3world7" + "nevermind92"; echo strlen(37); |
Rationale:
The solution:
If you have a string,
use
Booleans: Many values, if used in a boolean context, are "false-ish":
echo false == false; echo false == 0; echo false == 0.0; echo false == "0"; echo false == array(); echo $someUndefinedVar == false; // ?! |
echo false == 0; // true, as just noted. // == is not transitive (!): echo 0 == "00"; // true. echo false == "00"; // false?! echo 0 == "-0"; // true. echo false == "-0"; // false?! echo 0 == 0.0; // true. echo false == "0.0"; // false?! |
Caution: There are also the boolean operators with spelled-out names,AND andOR . Do not use them! They are just like&& ,|| except that they have unexpectedly low precedence (less than the assignment operators2 Use parentheses to force precedence if you are doing something unusual (or even, just use parentheses routinely, so that you never even need to think twice about precedence!).
Upshot:
PHP has
home—lects—hws
D2L—breeze (snow day)
©2017, Ian Barland, Radford University Last modified 2017.Jan.29 (Sun) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |