PHP Custom Error Handling: Part 2

July 1st, 2005

Before you can actually handle errors, you’ll need to have your xHTML ready to slot into a PHP function. You could do this in many ways; like by hard-coding xHTML into the error handling code, but I find this to be a little cumbersome, especially if you want to use the error handling code again. I find making a page class the easiest way to avoid unnecessary code copy and pasting:

class Page
{
var $page = '';  (1)
var $title = '';
	function Page ($title)
        {
		$this->title = $title;
		$this->addHeader(); (2)
	}

	function addHeader()
        {
		$this->page.=<<<EOD (3)
<html>
	<head>
		<title>$this->title</title>
	</head>
	<body>
EOD;
	}

	function addCentreContent($centrecontent = ”)
        {
		$this->page.=<<<EOD
		$centrecontent
EOD;
	}

	function addFooter()
        {
		$this->page.=<<<EOD
		<p>Please contact the site admin at foo@example.com</p>

	</body>
</html>
EOD;
	}

	function returnPage() (4)
        {
		return $this->page;
	}
}
  1. Though you might not be familiar with classes, this example is fairly simple. This is the page variable that the member functions can access and add things to. When you create variables here in the class, they can be accessed through the ‘$this->variablename’ convention.
  2. The ‘Page’ function is known as the class constructor. In this case it takes a ‘title’ parameter, and automatically adds the header of the page through addHeader().
  3. This way of setting strings is known as heredoc. It’s easier to use this when you can’t be bothered to escape xHTML quotes. This code isn’t designed to be copied and pasted, so if you want to then just edit out everything in the line after <<<EOD
  4. You should always design classes so they don’t output anything on their own. Make a member function instead.

Look out for the last in the series, coming soon.

Comments are closed.