views:

83

answers:

2

I have a set of custom PHP scripts. They load a main PHP file (to include other files, set settings, etc.) From this script I'd like to insert a callback function that is called by the scripts that included the main file just before ending.

What I intend to do is make a simple custom output cache with ob_get_contents(). I want to do ob_start() in main.php, then have the callback function store the output.

+3  A: 

See register_shutdown_function:

Register a function for execution on shutdown

Example from the manual:

<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
karim79
+1  A: 

ob_start() can do what you want:

ob_start('store_output');

function store_output($output) {
  // do something with $output
  return $output;
}

When the output buffer is flushed, the function will be called. Output buffers can be nested.

cletus
What would happen if you called ie. ob_get_clean()?
Matthew Scharley
It would call the callback. Is that desired behaviour?
cletus
Oops, I should have looked at the PHP documentation first :). That's exactly what I need!
heyitsme
I don't know, I'm not the OP! I was just curious.
Matthew Scharley