Home > Programming, Tip, variable_substitution > Write neater php code with variable substitution

Write neater php code with variable substitution

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:

$day="Monday";
$temp="72";
echo <<<EOD

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

Sincerely Yours,
rc

EOD;

Advertisements
  1. December 10, 2014 at 5:45 am

    Touche. Sound arguments. Keep up the good effort.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: