Search code examples
phpvariablesundefined

PHP and undefined variables strategy


I am a C++ programmer starting with PHP. I find that I lose most of the debugging time (and my selfesteem!) due to undefined variables. From what I know, the only way to deal with them is to watch the output at execution time.

Are other strategies to notice these faults earlier (something like with C++ that a single compile gives you all the clues you need)?


Solution

  • This is a common complaint with PHP. Here are some ideas:

    1. Use a code analysis tool, such as Phan or PHP_CodeSniffer with phpcs-variable-analysis plugin. Many IDEs such as NetBeans will help also.

    2. Just run the code. PHP doesn't have an expensive compilation step like C++ does.

    3. Use unit testing. Common side effects include: better code.

    4. Set error_reporting(-1), or the equivalent in your ini file.

    5. Get xdebug. It's not preventative, but stack traces help with squishing bugs.

    6. isset(), === null (identity operator), and guard clauses are your friends.

    Loose and dynamic typing are a feature of the language. Just because PHP isn't strict about typing doesn't mean you can't be. If it really bugs you and you have a choice, you could try Python instead—it's a bit stricter with typing.