Thursday, September 15, 2005

Double Quotes, Not Single Quotes

Posted by Phil Aaronson at 10:26 AM

I can't count the number of times I've made this same, single quote vs. double quote mistake over the years. In this latest stumble I was writing a bit of PHP code, using xpath. The line in question looked like this:

... $this->xml->xpath('//experiment[id=$id]') ...

Which is trying to say, look for all the <experiment> tags which have a child <id> tag whose value matches the value in $id. The only problem, when you run this you get one strange error message.

Unexpected PHP error [xmlXPathEval: 1 object left on the stack] severity [E_WARNING] ...

So of course, I stared at it for too long. Then pulled a couple coworkers into my cube in the vain hope that they could save me from myself. Eventually the light bulb went off, I should have written this of course:

... $this->xml->xpath("//experiment[id=$id]") ...

Damn I hate that. In PHP, like Perl before it, and like shell scripts before that, single quotes are for literal strings. Double quotes are for variable substitution, and I really wanted the variable $id to be replaced with its value. I'm getting too old.

2 Comments:

Blogger Steve R said...

Is there any reason other than performance not to just use double quotes all the time? It may sound lazy, but those errors would be prevented.

9/15/2005 2:55 PM  
Blogger Phil Aaronson said...

There are times when you want the string to be explicit. I seem to go back and forth between the two as my default, and get burned either way. I can never seem to remember. I probably should just give up and use 'this '.$var.' that' all the time, and never use double quotes.

9/15/2005 3:11 PM  

Post a Comment

<< Home