To NULL or Not to NULL

I’ve found programmers that I’ve worked with lately don’t like my use of null declarations in PHP. I come from a Perl and JavaScript background (with just enough C++ to be dangerous but not particularly useful), so I tend to declare variables before assigning them values (granted, it’s not a requirement in Perl, just a good idea).

If it adds to the complexity (and/or size) of code, why do it?

Yes, it will make the file a little bit larger…but I’ve never seen—or heard of—a minimized PHP file. Minimizing is great for client-side code (primarily JavaScript, HTML, and CSS) but unnecessary when servers handle the workload. You can find discussions of single- vs. double-quotes all over the Internet, even on PHP.net, but declaring variables in PHP seems odd because there’s no requirement to do so (technically, a variable in PHP has a NULL value when declared…but that doesn’t mean you won’t flag a notice).

Why do I [usually] declare NULL?

  1. Clarifying code; by declaring everything before I use it, I know what variables to look for later when I’m debugging (OOP PHP does this out of necessity with class-level variables)
  2. When using an IDE, the software auto-references those variables later; if I don’t have a matching variable, it won’t reflect in the IDE and I can catch typos before they become time-sucking issues
  3. Finally, PHP flags a notice-level error when a variable is referenced that has not been pre-declared; not everyone knows to turn off notice-level errors, and it’s a waste of log space (and effort to dig through logs full of notices)

I highly recommend working with other programmers; I believe it makes us better coders, we learn new ways of doing things and thinking about things. For continuity, you need to agree on programming conventions. I’m not overjoyed about giving up NULL declarations, but all things change—Facebook just released their fork of PHP, Hack.

Leave a Reply