Seva's notes

Wisdom, Awareness, Responsibility :)

Archive for September 2009

Variable declaration in PHP

with 2 comments

Today while playing around PHP and stuff I have been thinking of patterns of handling optionally existing variables.

The 2 most commonly used ones are:


if (isset($var) && $var != null) doSomething($var);
// or
if (isset($var) && $var != 0) doSomething($var);
// or
if (isset($var) && ($var != '') doSomething($var);

if (!isset($var)) $var = something();

However my experience points me that in the majority of the cases it’s enough to check the boolean value of the variable to proceed:


if ($var) doSomething($var);

if (!$var) $var = something();

Which reads very kosher. But then we have a problem of getting notice that the variable is undefined, which is not kosher.

So the way kosherize the snippet is to enforce variable definition before usage. Meaning we would like to either use its value if it’s defined, or to initialize it with null. But of course I don’t like to use isset() for that. So what to do? I found an answer!


$var = &$var;

As you can see in this way you declare further usage of the variable. If the variable exists – it does nothing. If it’s not it is silently initialized with null. No notices are yielded. Also it’s better than if(isset()) combination because of readability – the only alphanumeric tokens on the line are variable names.

Isn’t it nice?

Written by Seva

2009-09-28 (September 28) at 02:21:10

Posted in development, php, thought

Tagged with

SyntaxHighlighter

leave a comment »

Shame on me! I’ve discovered that wordpress.com provides syntaxHighlighter functionality just today. So I hurry to report that the only 2 posts in this blog, which contain code snippets have been immediately converted:

<a href="https://sevalapsha.wordpress.com/2008/06/26/copy-nodes-xml-documents-java-dom/">
    Copying nodes between XML documents with Java DOM
</a>
&amp;
<a href="https://sevalapsha.wordpress.com/2008/08/11/prototype-google-analytics-javascript/">
    Prototype styled Google Analytics javascript snippet
</a>

BTW, isn’t it weird I don’t have one snipped in PHP yet?

Written by Seva

2009-09-16 (September 16) at 09:14:52

Posted in html, java, javascript, php, software, web, xml

Tagged with