As you progress in a language, you'll probably end up getting bored or better yet, attempting to figure out the limits of a language. I'm getting to that point with PHP. Along the way, I wanted to find some neat tricks to either improve the performance of my code, or to make my code more compact, even perl-like (i.e. one liners). I find a neat little trick you can do in a string that's not very well known.
For the longest time, I would concatenate strings together if I wanted to use a method call or remove single quotes from hashes if I'd use them in a string. For instance:
$str = "Hello " . $this->getFirstName() . " " . $this->getLastName();
$out = "My name is $arr[fname] $arr[lname]";
It's said that both have some performance issues. In perl, the second one would be considered decent format, since they often discourage you from quote in a hash. However, in PHP, the second form is considered a bit slower because of some internal conversions that occur with the interpreter. So how can we handle this in a slicker manner? Use curly braces {}.
$str = "Hello {$this->getFirstName()} {$this->getLastName()}";
$out = "My name is {$arr['fname']} {$arr['lname']}";
Both styles are considered good form in PHP, if not bulking up your strings a bit. But you can avoid nasty concatenations or some performance hits by doing this.
Another little trick for handling variable interpolation, especially if you do a lot of inline messages (which isn't a good thing to do, but sometimes can't be helped), is using the heredoc format. Heredoc is a nice technique for avoiding the string concatenation problem. It makes the code appear a little uglier, but you don't take the performance hit of making something more readable by forcing the interpreter to work a little harder. The format goes like this:
$str<<<EOL
My favorite Japanese famous women are:
1) Reina Miyauchi
2) Norika Fujiwara
3) Shiho
4) Kaori Kawai
5) Ryoko Yonekura
EOL
Perl and other Unix scripting languages provide similar mechanisms. You can put variables and even make method calls in the heredoc as well. In terms of when to use such a device, my recommendation is SQL when you need to create long statements and lack some nice ORM to handle this internally for you. If you have to create email messages or insert HTML into your code, you might as well just skip right over to a templating system like Smarty instead. Of course, if your application is small, then a heredoc wouldn't be considered out of the question either.
Trackbacks: (Trackback URL)
