Article

Object Oriented PHP: Paging Result Sets

Page: 1 2 3 4 5 6 7 Next

Don't be a Square

A RectangleOkay, let's face it: rectangles haven't been interesting since 2nd grade geometry. But they make a conveniently simple example for us to get started with, and if you actually did get into Web development hoping for manual labour, you can pretend they're bricks.

So let's say some 2nd grader who's failing geometry has paid you to write a PHP script that performs calculations on rectangles. With the market downturn you're in no position to pick and choose, so you take the job.

You start out with a simple HTML form to allow the student to enter the width and height of a rectangle:

<form action="domyhomework.php" method="get">  
Width: <input type="text" name="w" /><br />  
Height: <input type="text" name="h" /><br />  
<input type="submit" />  
</form>

Now, domyhomework.php -- the script that will process this form -- could simply take the width and height and calculate the characteristics of the rectangle:

<?php  
$area = $w * $h;  
$perimeter = ($w + $h) * 2;  
?>  
<html>  
<body>  
<p>Width: <?=$w?><br />  
  Height: <?=$h?></p>  
<p>Area: <?=$area?><br />  
  Perimeter: <?=$perimeter?></p>  
</body>  
</head>

Nice and simple, but if you gain a reputation for writing rectangle scripts (hey, it could happen!), you might get tired of writing the code to calculate the area and perimeter over and over again.

If you've learned about PHP functions, you might decide to write two functions to perform these calculations in an include file. Let's say you write a file called rect.php, which contains just the following code:

<?php  
function rect_area($width,$height)  
{  
 return $width * $height;  
}  
function rect_perim($width,$height)  
{  
 return ($width + $height) * 2;  
}  
?>

You can then use these functions in any file that needs them. Here's our revised domyhomework.php:

<?php  
require('rect.php'); // Load rectangle functions  
$area = rect_area($w,$h);  
$perimeter = rect_perim($w,$h);  
?>  
<html>  
<body>  
<p>Width: <?=$w?><br />  
  Height: <?=$h?></p>  
<p>Area: <?=$area?><br />  
  Perimeter: <?=$perimeter?></p>  
</body>  
</head>

Now, this is all well and good, but with Object Oriented Programming, we can do better!

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links