Object Oriented PHP: A Gentle Introduction

Here we are, together again with yet another article, furthering our coding knowledge while we learn to program. Let me start by saying what this tutorial is not; it’s not an introduction about using PHP, although the concepts used are fundamental. In this tutorial, we will consider the rudiments of Object Oriented Design (OOD) using PHP. Given that OOD involves many broad concepts, we will focus our attention on the basics, so we don’t overwhelm or confuse any of our readers.

PHP is primarily known for being a ubiquitous server-side scripting language, heavily used in web development. However, it is rarely used like a general purpose programming language. However, it is flexible and powerful enough to be used in this way. In the forthcoming examples, we will get a first-hand account of just how effective it is when used in this manner.

Object Oriented Design is a methodology or approach in which a collection of data members and operations (state and behavior) are consolidated into a single unit/object and executed to solve a particular problem. In PHP, as well as most programming languages, classes are the mechanism by which this approach is possible.

OOD has four major principles that require a cursory understanding: Abstraction, Encapsulation, Inheritance and Polymorphism. A generic description of each is presented below. However, I encourage you to research these principles and in order to gain an in-depth understanding of each one. This will greatly enhance how you use OOD in your programming:

  • Abstraction – captures the critical features of an object while suppressing unnecessary details
  • Encapsulation – prevents outside access of internal data, preserving its integrity
  • Inheritance – supports reuse, providing the ability to define new classes/objects while specifying differences
  • Polymorphism – allows different classes/objects to handle the same data in different ways

The prerequisite to working with classes is understanding how to manipulate and store data in computer memory and defining, declaring, and calling functions. This is fairly straight forward using PHP.

If I was a part of the broad readership, which I am, committing my valuable time to read this article, I imagine the burning question that I would have, which I don’t, would be: why use OOD in PHP? What’s the benefit? Trust me, we will answer this question and will see exactly why. It is said: “a picture is worth a thousand words”. In our case, it’s screen shots that will give us a stunning revelation on the benefits of using OOD in PHP in far less than what would equate to a thousand words.

Let’s cut the small talk, and get to work with some solid examples.

The first thing we need to do is to get a working environment. For this tutorial, I will be using MAMP (My Apache MySQL PHP) for OS X. It’s a popular webserver that offers database and scripting language support. This will serve us well, considering that PHP is a scripting language that was designed for web development. I recommend that you go to https://www.mamp.info/en/ and download the version of MAMP that your system will accommodate (download the free version, unless you have deep pockets and want to purchase the pro version). I will be using OS X, but Windows and Linux users will be able to follow along with the examples.

Once MAMP is downloaded and installed, launch the application:

Object Oriented PHP_A Gentle Introduction-1.0
Figure 1.0 MAMP Application Launch

Select the Launch MAMP button.

Object Oriented PHP_A Gentle Introduction-1.1
Figure 1.1 MAMP WebStart page

This is our default home window when starting MAMP. From this page, we can quit the application, start servers, or configure the preferences.

Let’s select “Preferences” and then select the “Ports” tab:

Object Oriented PHP_A Gentle Introduction-1.2
Figure 1.2 MAMP Preferences

If your port settings do not look like Figure 1.2, select the “Set Web & MySQL ports to 80 & 3306” button.

Now, select the “PHP” tab:

Object Oriented PHP_A Gentle Introduction-1.3
Figure 1.3 MAMP PHP configuration

Here, we want to ensure that the latest version of PHP is accepted, which is 5.6.10 in this case (Standard Version will depend on version of operating system you’re running. Currently, I am running OS X 10.7.5).

Now, select the “Web Server” tab:

Object Oriented PHP_A Gentle Introduction-1.4
Figure 1.4 MAMP Web Server configuration

By default, the “Apache” radio button will be selected. This is the configuration that we want. The document root will also be Applications/MAMP/htdocs for OS X, and some variant of this for other systems (this is where our PHP scripts will live). This is what we want.

Select the “Okay” button. The preferences window will close. Select “Start Servers”.

The Apache Server and MySQL Sever status boxes in the upper right hand corner will turn green if there are no errors in our configuration. The WebStart page will remain open as long as our servers are in use (just minimize it). In addition, a default Webpage will open:

Object Oriented PHP_A Gentle Introduction-1.5
Figure 1.5 MAMP default server webpage

Now that we have our environment in place, let’s start writing some code. First, create a folder (name of your choice) inside of our htdocs folder. Second, open a text editor (and don’t use any word processing application like Word, Pages, etc. The formatting will cause issues. I’m sure you already know this, but a reminder is good every now and then). Create a file that looks like Figure 1.6, which is our first class.

Introductory Class specific commands used in PHP:

  • class – creates the class definition that will include data members and data methods
  • new – create an instance of a class
  • –> This is an object operator; used to call a method on an instance

Object Oriented PHP_A Gentle Introduction-1.6
Figure 1.6 Create a class in a PHP file

We start our script by inserting our PHP opening tag (<?PHP). But wait a minute, where is the closing tag? Did we forget it? No! Omitting the closing tag is common practice when using a basic text editor (no line count or code hints), since it offers a solution for avoiding blank spaces and stray characters behind the closing tag. We then use the class keyword to make a class: User. In the next line we define our class constructor with the keywords public function __construct. We add the variable $city as the parameter. Inside our constructor method (a function inside of a class) we echo the city to the screen. Save this file as index.php inside of the folder you created inside of htdocs. Now let’s instantiate an object with this class.

Object Oriented PHP_A Gentle Introduction-1.7
Figure 1.7 Instantiate an object with User class

We added a new line that creates an instance/object of our User class. $NY is the variable to which our object will be assigned. We use the new keyword to an instance of the User class. We added a string (New York) as our parameter to pass to our class constructor. Now, let’s run our program. Open your web browser and enter localhost/MyFolderName/. Because the file is named index.php, there is no need to add that to our url. If an index.php is in our root folder, it will be selected implicitly.

Object Oriented PHP_A Gentle Introduction-1.8
Figure 1.8 Run index.php file

If we don’t have any errors, your browser will display what is shown in Figure 1.8. Let’s look at a simple example of Inheritance at work since we have a class to work with.

Object Oriented PHP_A Gentle Introduction-1.9
Figure 1.9 Create 3 instances of the User class (Inheritance at work)

The only thing different is that we added two more instances of our User class ($LA and $MI). When we run our application in the web browser, we get what’s displayed in Figure 2.0.

Object Oriented PHP_A Gentle Introduction-2.0
Figure 2.0 Browser displays several User instances

As we can see, defining and instantiating a class is fairly straightforward. However, all we’ve demonstrated so far is that we can create a class and access the included data member, but no behavior.

We will now look at another example. Let’s create a new file (get_address.php) inside the folder we created in our htdocs folder (working folder), and enter what is displayed in Figure 2.1.

Object Oriented PHP_A Gentle Introduction-2.1
Figure 2.1 Create new php file (get_address.php)
This is a more complete example of a class. The class has a data member ($address), constructor, and a member method (getAddress). When we used $city as a variable in Figure 1.6, we did not explicitly make it a public class member. But, by default, if not designated, data members are public. Here, we explicitly defined $address as public. In our constructor, this time around we did not echo our data member, we just assigned the data passed to it as the value of the variable. We also added a member method (behavior) to display the address that the user enters. We also enter a string of an address in the class parameter. Finally, we use our class object $del to access our member method getAddress(). Let’s save our file, and run our application by opening our browser and entering the url to our file: localhost/MyFolderName/get_address.php.
Object Oriented PHP_A Gentle Introduction-2.2
Figure 2.2 Run get_address.php application
If no errors were returned, your browser should display something similar to what’s in Figure 2.2. Now, we are going to switch things up a bit and separate our code from the user output, as this is what will be seen more often in real world practice. Create a new file called user.php, and place it in your working folder. Ensure that the user.php looks like Figure 2.3.
Object Oriented PHP_A Gentle Introduction-2.3
Figure 2.3 Create user.php file

In our user.php file, we copied our class data from our get_address.php file. We can immediately see that we added another class member ($phone), and that we defined it as a private member (highlights the Encapsulation principle). We also added a public member method getPhone (behavior). Like getAddress, it returns data to the browser screen (phone number). Let’s open our get_address.php file again and edit it to look like Figure 2.4.

Object Oriented PHP_A Gentle Introduction-2.4
Figure 2.4 Edit get_address.php file

In our get_address.php file, we added a file include to have access to the User class inside of the user.php file. We also added an html heading tag (<h3>), as a bold title (User Info). Finally, we used our object $del to access the getPhone method. Let’s run the application. Enter the following url in your browser: localhost/MyFolderName/get_address.php.

Object Oriented PHP_A Gentle Introduction-2.5
Figure 2.5 Run get_address.php
If there were no errors, your browser should display the same data that’s displayed in Figure 2.5. There are a few things to mention. We can access our public data members directly; we can really avoid using our getAddress method, and access the $address member directly. Let’s have a look at that.
Object Oriented PHP_A Gentle Introduction-2.6
Figure 2.6 Access the $address member directly
We replaced the getAddress function with the $address data member. Now, let’s see what happens when we run our get_address.php file.
Object Oriented PHP_A Gentle Introduction-2.7
Figure 2.7 get_address.php result of changing the getAddress method

The same data is displayed on the screen, but the formatting that is displayed in Figure 2.3 getAddress method is not used. Now, let’s see what happens when we try to access our phone data member directly.

Object Oriented PHP_A Gentle Introduction-2.8
Figure 2.8 Change getPhone method to the $phone data member

This time we added the $phone data member in the place of the getphone method. When we run our get_address.php file again, we get the following:

Object Oriented PHP_A Gentle Introduction-2.9
Figure 2.9 get_address.php result from changing the $del object getPhone method to $phone data member

We can see that the phone number is not displayed. That highlights the Encapsulation principle. Because the $phone data member is private, the outside world does not have direct access to private data members. It can only be accessed via a member function.

We will end our examples here, so that you can digest what we’ve covered so far, and will not become overwhelmed with what can be a very complex topic.

These examples are very rudimentary in nature, but, provide a gentle introduction into using OOD in PHP. As you go through this tutorial and take the time to understand the steps, they will broaden your approach to using object oriented design, by identifying when and where it would be a benefit to use it. This is a brief introduction and only scratches the surface of OOD. After you digest what’s in this article, there is plenty more to learn. Study well and be prepared for a future installment of using OOD in PHP.

Be the first to comment

Leave a Reply

Your email address will not be published.