Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 463
tru7 Avatar asked Aug 25 '10 10:08

tru7


2 Answers

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

  1. Use a code analysis tool. 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.

like image 160
cbednarski Avatar answered Oct 10 '22 14:10

cbednarski


Log your E_NOTICE messages to a text file. You can then process logs with automated scripts to indicate files and lines where these are raised.

like image 43
Mchl Avatar answered Oct 10 '22 13:10

Mchl