Archive for the ‘variable_substitution’ Category

Write neater php code with variable substitution

April 14, 2010 1 comment

Whenever I see php codes like the following:
$html="<ul><li><a href=\"".$href."\" class=\"".$class."\">click</a></li></ul>";

I feel dizzy. With variable substitution, the above code can be easily written as
$html="<ul><li><a href='$href' class='$class'>click</a></li></ul>";

( Of course if you want to be strict about the resulting html code, you can also use function sprintf like the following:

$html=sprintf('<ul><li><a href="%s" class="%s">click</a></li></ul>', $href, $class);


Variable substitution also works with arrays, curl brackets are required to put around the array element, for example:

$a=array('food'=>'orange', 'name'=>'Somebody');
echo "{$a['name']} ate {$a['food']} today.";

Variable substitution also works great with heredoc:

echo <<<EOD

Dear My Friend,
$day’s temperature is $temp. Let’s go out and have some fun!

Sincerely Yours,