How to maintain global variables when you use ob_start?

1k Views Asked by At

I have this problem during 1 week, I need to solve this.

If I test this code, it works well:

<?php

$t = 3;

function callme()
{
   global $t;
   echo "The value of t is " . ($t == null?"null":$t);
}

callme();

// output: The value of t is 3

?>

BUT, if I use ob_start() I lost the global variables:

<?php

$t = 3;

function callme()
{
   global $t;
   echo "The value of t is " . ($t == null?"null":$t);
}

register_shutdown_function( "callback_on_exit" );

function callback_on_exit()
{
   $output = ob_get_contents();
   ob_end_clean();
   echo str_replace( "The", "My", $output );
}
ob_start();
callme();
exit;

    // output: My value of t is null

?>

The solution I found is to add "global $t; at the top of the script. But there is no well, because on scripts or applications with several global variables, how I can declare all variables or how I will now what variables will exists. Any suggestion?

0

There are 0 best solutions below