Wednesday, July 28, 2010

Thursday, July 1, 2010

HEREDOC: a great way to build long strings

The PHP HEREDOC feature: a great way to build long strings, such as when You're writing PHP code to spit out HTML.  For example:

Hideous old method:
$my_string = "".
"<table>\n" .
"    <tr>\n".
"        <td>What's for lunch?</td>\n".
"    </tr>\n".
"</table>\n";

echo $my_string;

Magnificent Heredoc method:
$my_string = <<<COOLSTUFF
<table>
    <tr>
        <td>What's for lunch?</td>
    </tr>
</table>
COOLSTUFF;

echo $my_string;

see: http://www.tizag.com/phpT/strings.php

Note that the Heredoc syntax is rather unforgiving.  That terminating "COOLSTUFF" line must be NON-indented, and You can't even have spaces or tabs after it on the same line, or it won't work.  But if You treat it nice, it will treat You nice.

Variables in a CSS style sheet

Here's something I learned about PHP yesterday that was just so much fun I have to share it with You.  Of course, You probably learned this on Your mother's knee:

I found out how to define and use variables in a CSS style sheet.  Very convenient when You want to, say, define a color once in Your CSS sheet and then use it multiple times throughout that CSS file.  I gather that normally CSS doesn't support variables, but there's a nice way around that limitation.  It basically involves using a style.php file rather than a style.css file, and then embedding variables in the CSS with php.  see: http://sperling.com/examples/pcss/