PHP - 在循环中使用include的替代方法

I have a chunk of HTML code (with some PHP vars echoed inside of it) that I need show on multiple times (inside a loop) AND on multiple pages.

So how to keep it DRY?

My ideas admittedly were not brilliant:

  • Putting it in a separate file and including - but then I'll do an include inside a loop and it showed like bad practice.

  • Putting it in a function - but then I have to make variables global plus it just doesn't look to me like functions are meant for such usage.

Is there a better way? Is this where maybe OOP has a solution? (I run php 5.3)

Use templates.

Just write your loop inside of the template, as well as all other presentation code.

<h1>Some list</h1>
<ul>
<?php foreach($data as $row): ?>
  <li><?=$row['name']?> whatever your block code goes here</li>
<?php endforeach ?>
</ul>

so, no need to include anything at all.

For the multiple pages you may wish to make a helper function, called from the template.

couldn't you pass the specified variables you need into the function?

 function foo($name, $something) {
      echo '<b>' . $name . '</b> is ' . $something;
 }

Then, variables do not have to be global ... or have the function return the string, versus the echo in the above example.

Yes OOP can give you an hand, i created a set of classes to show social plugins (Facebook , G plus, twitter) on my pages linked to various elements.

I set up the helper class atthe top of my page

$socialPlugins = new SocialPluginsHelper(array(
        SocialPluginsHelper::HTML_AFTER_BUTTONS => '<div class="clear"></div>',
        SocialPluginsHelper::HTML_BEFORE_BUTTONS => '<div class="clear"></div>',
        SocialPluginsHelper::STYLE_OF_WRAPPER => 'margin-top:5px;',
        SocialPluginsHelper::CUSTOM_PLUGIN_STYLE => array(
                "TwitterButton" => "width:69px;",
                "FacebookLike" => "width:146px;")
)
);
$socialPlugins->add(PluginFactory::create("FacebookLike", array(FacebookLike::FB_WIDTH => "146")));
$socialPlugins->add(PluginFactory::create("TwitterButton"));
$socialPlugins->add(PluginFactory::create("Gplus")); 

and then inside a loop i just call

$socialPlugins->renderAllButtons(array("FacebookLike" => array(FacebookLike::FB_HREF => $url)));

this is as dry as i could keep, you might need a different architecture based on your specific needs, this is just to give you an idea