Location: PHPKode > scripts > Output Buffering handler > output-buffering-handler/OBH.class.php
<?php

//Escape constants
define("ESCAPE_SINGLE_QUOTES", "'");
define("ESCAPE_DOUBLE_QUOTES", '"');

class OBH {
	//Handler and globals arrays
	private $handlers = array();
	private $globalvars = array();
	
	function __construct()
	{
		//Set the OB handler as this classes (notice & for reference, not copy) runAllFunctions function
		ob_start( array( &$this, 'runAllFunctions' ) );
	}
	
	//Function to set a variable as global. First and foremost to allow easy access to class objects.
	public function setGlobal($var_name)
	{
		array_push($this->globalvars, $var_name);
	}
	
	//Function to add a handler (through PHP expressions)
	//All occurences of %text% will be converted to the variable containing input
	//Take a PHP expression as input. This will be evaluated as a function call that will return a value.
	//Using PHP expression to allow class functions to be run easily.
	//Remember to use the setGlobal function to access class from the outside!
	public function addH($php_exp, $escape = ESCAPE_SINGLE_QUOTES)
	{
		array_push($this->handlers, array('exp' => $php_exp, 'esc' => $escape));
	}
	
	public function addHFirst($php_exp, $escape = ESCAPE_SINGLE_QUOTES)
	{
		array_unshift($this->handlers, array('exp' => $php_exp, 'esc' => $escape));
	}
	
	//Function to run all set handlers
	//Must be public since ob_start is external
	public function runAllFunctions($in)
	{
		//First we make every variable that has to be global, global
		for ($o = 0; $o < count($this->globalvars); $o++)
		{
			//Variable variables.... I know it's not pretty, but why not ^^
			global ${$this->globalvars[$o]};
		}
		//Then we set $in to what each of the functions return when given the input escaped by ' or " through the use of eval.
		for ($i = 0; $i < count($this->handlers); $i++)
		{
			eval('$in = '.str_replace('%in%', str_replace($this->handlers[$i]['esc'], '\\'.$this->handlers[$i]['esc'], $in), $this->handlers[$i]['exp']).';');
		}
		//And finally we return the modified $in to whatever function tried to retrieve the output buffer (probably ob_end_flush() set implicitely at the end of the script)
		return $in;
	}
};

?>
Return current item: Output Buffering handler