PHP banana peels: common PHP mistakes and and how to avoid them

PHP banana peels: common PHP mistakes and and how to avoid them

Last updated:
  • comparison operators

using !$foo==="bar" when you really mean $foo!=="bar". In most cases, the second option is what you want;

  • UTF-8 and Unicode usage

functions to use when dealing with UTF-8 string: - mb_strtolower("FÚÛÙ-BÅÃÄ","UTF-8")

  • **_once functions*

require_once and include_once return only true if you try to require/include a file that has already been included (i.e. if you store code in individual files, use require or include rather than their _once counterparts otherwise it will return true rather than the code you want for the next calls after the first.)

  • method names

instance methods in a class can't have the same name as the Class itself or PHP will think it's a constructor (this is supposed to enable backward-compatibility with older PHP versions that used a class' name as the name for the constructor)

  • spaces or newlines after closing php tag

this is a big NONO. If you have whitespace or newlines after the php closing tag (?>) you'll get all sorts of hard-to-debug error messages. It's better to have no closing php tag if you file contains only PHP (i.e., no embedded HTML). And yes, it is allowed not to have a closing tag on a PHP file.

  • case or

if you want to use or (||) operators inside a case call, this is the right way to do it:

    switch ($str) {
        case 'foo':
        case 'FOO':
            //do stuff
        //... more stuff 

In other words, no using || or or after case keyword. (stackoverflow question on using switch/case with or)

Off topic link : 7 ways to reuse a banana peel

This is a w.i.p. (work in progress).

Dialogue & Discussion