Note that there are some explanatory texts on larger screens.

plurals
  1. POHow could you create a "content_for" equivalent in PHP?
    text
    copied!<p>I've been working on a small page in PHP, one that doesn't need the power of a full-fledged framework behind it. One thing that I'm really missing from previous work in Ruby-on-Rails is the ability to effectively pass content up the page using "content_for".</p> <p>What I was wondering is, how could you create a page lifecycle that would accomplish this same effect in PHP?</p> <p>So, here's a simple example:</p> <p>Let's say you have a template that defines an index page, just a recurring header and menu you want to use on all your pages. So your <code>index.php</code> file looks basically like this:</p> <pre><code>...header stuff... &lt;body&gt; &lt;?php include $file.'.php'; ?&gt; &lt;/body&gt; ...footer stuff... </code></pre> <p>EDIT: Thanks for the tips on URL security, but let's just assume I'm getting the user request safely :)</p> <p>Now, lets say in the header you want to put this:</p> <pre><code>&lt;head&gt; &lt;title&gt;&lt;?php echo $page_title; ?&gt;&lt;/title&gt; &lt;/head&gt; </code></pre> <p>It would be nice to be able to specify the title in the included file, so at the url <code>http://example.com/index.php?p=test</code> you're loading <code>test.php</code>, and that file looks like this:</p> <pre><code>&lt;?php $page_title = 'Test Page'; ?&gt; ... rest of content ... </code></pre> <p>Now, obviously this doesn't work, because the including page (index.php) is loaded before the variable is set.</p> <p>In Rails this is where you could pass stuff 'up the page' using the <code>content_for</code> function.</p> <p><strong>My question is this: What would be the simplest, leanest way that you all can think of to effect this kind of 'content_for' functionality in PHP?</strong></p> <p>Ideally I'd like suggestions that don't involve strapping on some big framework, but some relatively light boilerplate code that could be used in a lot of different applications.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload