Article

Object Oriented PHP: Paging Result Sets

Page: 1 2 3 4 5 6 7 Next

Rectangle Calculator 2.0

Before we dive into our new rectangle calculation script, we need to learn how to create an object out of a class. That is, we've laid down the blueprints for a Rectangle, but we have yet to actually create one. Here's how:

new Rectangle(width, height)

The keyword new tells PHP that you want it to create a new object, and that's what is responsible for the magic here. By saying new Rectangle, we're telling PHP to instantiate our Rectangle class. Now, remember that the constructor function we declared took two parameters -- the width and the height of the rectangle to be created -- so we must specify those values here (width and height).

So, for example, to create a 10 by 20 rectangle and put it in a variable called $myRectangle, we'd use the following line of PHP code:

$myRectangle = new Rectangle(10,20);

We could change the rectangle's width:

$myRectangle->width = 50;

And then print out its area:

echo $myRectangle->area(); // Prints out '1000'

More importantly, we can create two rectangles, and play with them together:

$rect1 = new Rectangle(10,20);    
$rect2 = new Rectangle(30,40);    
echo $rect1->area(); // Prints out '200'    
echo $rect2->perimeter(); // Prints out '140'

Now that we know how to create and use a Rectangle object, we can create a revised domyhomework.php script:

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

See how elegant the code is? We create a rectangle by specifying its width and height, and from then on the object handles all the details for us. All we need to do to determine the rectangle's area and perimeter is to ask for them by calling the relevant methods. This quality of OOP, where functionality is hidden away inside objects so the developer who uses it doesn't need to know how it works, is called encapsulation.

If you're interested in reading about the object oriented features of PHP in greater detail, I'll refer you to Chapter 13 of the PHP Manual. The basics we've seen to this point are enough for most uses of Object Oriented code in PHP.

But enough of rectangles! Let's now design something useful, shall we?

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

Sponsored Links