|
home—lects—exams—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 does have different types (including the standard booleans, ints, floats, strings, and arrays). However, it often plays exceedingly fast-and-loose with them — “type juggling” — which might makes it seem like PHP doesn't know about types.
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; // ?! |
// == is not transitive (!): echo 0 == "00"; echo false == "00"; // false?! echo 0 == "-0"; echo false == "-0"; // false?! echo 0 == 0.0; echo false == "0.0"; // false?! |
Upshot:
PHP has
1In human law, if you know something is wrong and don't report it, it's often criminal negligence. Why we don't hold PHP or certain other languages to the same standard, I don't know. ↩
home—lects—exams—hws
D2L—breeze (snow day)
©2015, Ian Barland, Radford University Last modified 2015.Sep.11 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |