MetaPhilter Doc

« TOC

Incorporating PHP

As of MePhi .5, PHP scripting elements are parsed within template files. It works much the same way executing regular PHP does, with two very important differences to keep in mind.

The output of MetaPhilter templates is buffered. It is not sent to the user as it is parsed. Because of this, while any PHP is being parsed, the print and echo functions in any PHP will send data to the browser before the requested template is sent.

For example, when the following appears in an index template...

<?php include '../mp/metaphilter.php'; ?>
<MPIndex>
  News goes here
  <?php print 'Science!'; ?>
...

...the output sent to the user is similar to this:

Science!
News goes here

To get around this sort of thing, PHP executed within scripts is actually eval'd and its returned value incorporated into the template being parsed. So, if you want PHP data placed directly into the template, you should return the value, rather than printing or echoing it:

<?php include '../mp/metaphilter.php'; ?>
<MPIndex>
  News goes here
  <?php return 'Science!'; ?>
...

That will return something closer to what you expected:

News goes here
Science!

The second issue is this: when a PHP script is accessed by the server, it is automatically parsed for functions, classes, etc. that are in the global scope of the script. Any PHP script elements in an index template automatically declare their global elements before the template is parsed. This can cause some confliction if you declare any functions or classes in the global scope of the script when using the standard PHP tags (<?php ?>).

For instance...

<?php include '../mp/metaphilter.php'; ?>

<?php
  function science() {
    return "Science!";
  }
?>

<MPIndex>
  <?php return science(); ?>
...

...will cause a Fatal error when accessed by the server because the science() function is declared in the global scope automatically, and then redeclared when parsed by the MetaPhilter template system.

MetaPhilter has introduced a new tag to compensate for this. The php tag is not a standard PHP tag and is therefore not parsed by the server when accessed. It is parsed by the MetaPhilter template system and won't cause any conflications.

Rewriting the code above like so...

<?php include '../mp/metaphilter.php'; ?>

<php>
  function science() {
    return "Science!";
  }
</php>

<MPIndex>
  <php> return science(); </php>
...

...will declare the science() function once and cause no conflictions. The function call to science() can use the standard PHP tags if you want, what's important is that you never declare any global PHP elements within them.