Basic Introduction of Object Oriented PHP
Over the next few articles I write, I hope to delve into the depths of PHP and some of the ways it can best be utilized. To get started, we’ll begin with object oriented PHP programming. If this concept is new to you, have no fear. As long as you have an understanding of PHP in general, it is really rather simple, especially if we step through it bit by bit.
Before we get too much farther, it is important to note that the code I’m going to show you won’t work in any version of PHP prior to version 5. PHP 4 is quickly being phased out as 6 is right around the corner. Smart move by the PHP authors!
You’ve probably gathered that object oriented programming is, well, oriented around objects. What is an object I hear you asking? Simple. An object is a person, place, or thing… a noun. See, I told you this stuff was easy. So lets think of some things. An airplane. A car. A bank account. A shopping cart. A book. Let’s take that book example and run with it.
A book, as with any other object, can have attributes. A book has a title, a set number of pages, an author, and maybe even a bookmark letting you know what page you are currently on. You can also do things with a book, such as flip to the next page, flip back a page, or maybe even skip ahead to the last page to get a sneak peak at how things will end up.
Can we represent all of this in PHP code? Of course! We just need to define these attributes and plug in the functionality into what is called a class. A class defines your object. You create a new class with the word “class” followed by the name of your object. As an object has structure and is defined, PHP needs to know where the class definition starts and stops. You do this with our good friends, the curly braces. Our empty class, defining the book object, will look like this:
class Book { }
At the top of your class, just after the first curly brace, we will set the attributes of the book. These variables should always be defined at the top of your class and, for the sake of this article, can be public (available from outside the class) or private (only available to code inside the class). There are other options, but we’ll save those for another day. Simply append the work “public” or “private” before the variable, like this:
class Book { public $title = ""; private $author = "" private $number_of_pages = ""; private $current_page = 1; }
Most of the variables aren’t set to anything specific yet, as we do not know what actual book it is going to represent until it is created, but more on that later. We do know, however, that we always start reading a book from the first page, so we can go ahead and set that variable right away.
Now let’s put some brains behind our new book class. Class methods, also commonly called functions, are the only way to handle functionality. You cannot have PHP code just floating around willy-nilly. These functions can also be noted as being public or private. Again, there are other options, but we’ll save those for another article.
In trying to keep the craziness to a minimum, we need to think this through. We want to be able to set the attributes of the book, see the title of the book, who wrote it, and flip to the next page, flip back a page, and jump to the end of the book. Notice there are a lot of functions that deal with pages? Why rewrite code to handle page turning again and again when we can simply write one function to handle the page turning and then have simple functions make use of that function? Confused? It will be easier to understand when you see it in action.
class Book { public $title = ""; private $author = "" private $number_of_pages = ""; private $current_page = 1; public function get_author() { return $this->author; } private function go_to_page( $page ) { $this->current_page = $page; } public function next_page() { $this->go_to_page( $this->current-page + 1 ); } public function previous_page() { $this->go_to_page( $this->current-page - 1 ); } public function jump_to_last_page() { echo "Sorry Charlie. No skipping ahead!"; } }
Whoa, there’s a lot of new stuff in there. Don’t worry. Remember, nice and simple, slow and steady. First off, note that most functions are set to pubic. This allows us to call them from outside of the code in the class, like from the code in which the object is going to be created. However, the go_to_page() function is marked as private. If you try to call it from outside of the class, it will blow up on you. This is convenient to keep people skipping around from random page to random page, but yet lets us go to specific pages from within the class proper. This keeps the power of going to pages in the control of the class, and ultimately in the hands of whoever is writing the class.
I’m sure you noticed the use of $this as well. Since objects live in their own little world, and many instances of an object can be created at any given time, you need to specify that you are talking about THIS specific instance of the book. The functions are not global in scope; you could not call the next_page() function from just anywhere in your application. It must be associated with a specific book, or we wouldn’t know how many pages were in the book to even know if we could turn the page again.
As it is now, even when we create a book object now, we don’t know how many pages are in it, since we have no way of setting the attributes in the book yet. Let’s fix that with what is called the “constructor” of the class. It should be the first function in the class, and can do anything you want it to do – or nothing at all. You define your constructor by creating a function named __construct. The two underscores are used by PHP to say “Hey, I’ve got a special function I’m defining for you here.” There’s several of these magic functions, but we’ll stick with the constructor for now. Oh, what’s that? Why’s the constructor magical? Well, you see the constructor gets called automagically when you instantiate the object. Because of this, you can pass the variables into the constructor at the time of instantiating the class. We’ll get to that in a minute.
class Book { public $title = ""; private $author = "" private $number_of_pages = ""; private $current_page = 1; public function __construct( $title, $author, $number_of_pages ) { $this->title = $title; $this->author = $author; $this->number_of_pages = $number_of_pages; } public function get_author() { return $this->author; } private function go_to_page( $page ) { $this->current_page = $page; } public function next_page() { $this->go_to_page( $this->current-page + 1 ); } public function previous_page() { $this->go_to_page( $this->current-page - 1 ); } public function jump_to_last_page() { echo "Sorry Charlie. No skipping ahead!"; } }
Sure, we’ve done absolutely no validation in any of these functions; I leave that up to you to develop. Realistically, you wouldn’t be passing in all these attributes anyway, but would rather likely be sending in a book ID and then looking up the attributes in a database. But we’re keeping things simple here, after all.
Notice that we can reference all the passed in variables directly by their name. But remember $this? Here we can see how a local variable and a class variable can co-mingle. You take the title and set it to be the title of THIS specific instance of a book. Still with me?
Great, we’ve got all our functionality in place, so let’s start playing with it.
Somewhere else in your application, you want people to be able to be able to work with books. Once you know what book someone is looking for, you can create a new instance of the book object for it and assign it to a variable.
$our_book = new Book( "The Cat In The Hat", "Dr. Suess", "20" );
We’ve just created a book called The Cat In The Hat by Dr. Suess that has 20 pages and has all the functionality a book should have. You can’t call the functions using $this from outside the class, however, as that wouldn’t allow you to have multiple books open at the same time. Instead, we use the variable to which we just assigned the new book.
To display the author, since the variable is private within the class, we must use the get_author() function.
echo $our_book->get_author();
The title is public, so we can simply pull that out of the class without a function, directly by variable name, since we defined it at the top of the class.
echo $our_book->title;
We’ve just finished reading page one of our book, so let’s turn the page.
$our_book->next_page();
Not a whole lot of text on these pages. Flip to the next one.
$our_book->next_page();
Ahhh, green eggs. Yummy! By creating a class for our books, and putting all book functions in that class, we have been granted two very important benefits when developing an application:
- A book can be accessed anywhere again and again. Let’s say you have a page that lists all your books and each of those listings links to a page about each specific book. There is no need to duplicate any of the functionality. It is all wrapped up in a pretty bow in the book class.
- Because all the book functions are together in one class, you only have one place to go if you want to modify your book functionality or add to it. Two years from now, you won’t want to go through twenty files searching for any code dealing with books; you’ll want to know that any book code is going to be in the book class. Sure, other files will reference the book class, but lots of references to one file containing all your book logic sure beats having the logic scattered across several different files.