Article

The PHP Anthology Volume 1, Chapter 2 - Object Oriented PHP

Page: 1 2 3 4 5 6 7 8 9 10 11 Next

Classes and Objects

A class is a “blueprint” for an object. That is, unlike a function that you’d declare and use, a class merely describes a type of object. Before you can do useful work with it, you need to create an object—an instance of the class—using a process called instantiation. Once you have an object, you can call the methods that are defined in the class.

Classes don’t contain only functions—they can also contain variables. To make the Page class we developed above more useful, we might want to group some variables with the methods, then instantiate the class into an object. Here’s the code for the revamped Page class; join me below for the explanation:

Example 2.4. 3.php (excerpt)

<?php  
// Page class  
class Page {  
 
 // Declare a class member variable  
 var $page;  
 
 // The constructor function  
 function Page()  
 {  
   $this->page = '';  
 }  
 
 // Generates the top of the page  
 function addHeader($title)  
 {  
   $this->page .= <<<EOD  
<html>  
<head>  
<title>$title</title>  
</head>  
<body>  
<h1 align="center">$title</h1>  
EOD;  
 }  
 
 // Adds some more text to the page  
 function addContent($content)  
 {  
   $this->page .= $content;  
 }  
 
 // Generates the bottom of the page  
 function addFooter($year, $copyright)  
 {  
   $this->page .= <<<EOD  
<div align="center">&copy; $year $copyright</div>  
</body>  
</html>  
EOD;  
 }  
 
 // Gets the contents of the page  
 function get()  
 {  
   return $this->page;  
 }  
}

The Page class has become a lot more useful in this version of the example. First of all, we’ve added a member variable (also called a field), in which to store the HTML:

 // Declare a class member variable  
 var $page;

The PHP keyword var is used to declare variables in classes. We can also assign values to variables as we declare them, but we cannot place function calls in the declaration. For example:

 // This is allowed  
 var $page = '';  
 
 // This is NOT allowed  
 var $page = strtolower('HELLO WORLD');

After the variable declaration, we have a special method called the constructor. This method is automatically executed when the class is instantiated. The constructor function must always have the same name as the class.

Constructors have no return value

A constructor cannot return any value. It is used purely to set up the object in some way as the class is instantiated. If it helps, think of the constructor as a function that automatically returns the object once it has been set up, so there’s no need for you to supply a return value yourself.

That said, you may still use the return command with no specified value to terminate the constructor immediately, if needed.

Inside the constructor we’ve used a special variable, $this:

 // The constructor function  
 function Page()  
 {  
   $this->page = '';  
 }

Within any method (including the constructor) $this points to the object in which the method is running. It allows the method to access the other methods and variables that belong to that particular object. The -> (arrow) operator that follows $this is used to point at a property or method that’s named within the object.

In the example above, the constructor assigns an empty string value to the $page member variable we declared at the start. The idea of the $this variable may seem awkward and confusing to start with, but it’s a common strategy employed by other programming languages, such as Java, to allow class members to interact with each other. You’ll get used to it very quickly once you start writing object oriented PHP code, as it will likely be required for almost every method your class contains.

Of the other class methods, addHeader and addFooter are almost the same as before; however, notice that they no longer return values. Instead, they update the object’s $page member variable, which, as you’ll see, helps simplify the code that will use this class. We’ve also used the addContent method here; with this, we can add further content to the page (e.g. HTML that we’ve formatted ourselves, outside the object). Finally, we have the get method, which is the only method that returns a value. Once we’ve finished building the page, we’ll use this to create the HTML.

All these methods access the $page member variable, and this is no coincidence. The ability to tie PHP code (the methods) to the data (the variables) that it works on is the most fundamental feature of object oriented programming.

Here’s the class in action:

Example 2.5. 3.php (excerpt)

// Instantiate the Page class  
$webPage = new Page();  
 
// Add the header to the page  
$webPage->addHeader('A Page Built with an Object');  
 
// Add something to the body of the page  
$webPage->addContent("<p> align=\"center\">This page was " .  
 "generated using an object</p>\n");  
 
// Add the footer to the page  
$webPage->addFooter(date('Y'), 'Object Designs Inc.');  
 
// Display the page  
echo $webPage->get();  
?>

To use the class, we’ve instantiated it with the new keyword. The object created from the class is placed in the $webPage variable. Through this variable, we have access to all the members of the object as we did with the $this variable above.

The first call to the addHeader method demonstrates the point:

$webPage->addHeader('A Page Built with an Object');

Only at the end, upon calling the get method, do we actually get anything back from the class. No longer do we need to worry about passing around a variable that contains the contents of the page—the class takes care of that.

Avoid output in classes

Instead of get, we could have endowed the Page class with a method called write to send the page code to the browser immediately. This would have made the code above slightly simpler, as the main script would not have had to get the code from the object and echo it itself. We avoided this for a reason.

It’s usually a bad idea to output directly from inside a class (with statements and functions such as echo and printf); doing so will reduce the flexibility of your classes. Allowing the value to be retrieved from the class gives you the option of performing additional transformations on it before you send it to the browser, or use it for some other purpose entirely (like putting it in an email!).

Notice also that the number of lines of code we have to write to use the class is fewer than were required in the earlier examples. Although it’s impossible to determine good application design by counting the number of lines of code, it is clear that the class has made the procedural code that uses it much simpler. From the point of view of people reading the code, it’s already fairly clear what’s going on, even without them having to look at the code for the Page class.

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