Object Oriented PHP: The Basics

When dealing with PHP a lot of times you start repeating code over and over. OOP or Object Oriented PHP can solve a lot of the hassle. It allows you to make classes that you can use numerous times without modifying the code. In this tutorial we will go over the basics of working with Object Oriented PHP.

What is Object Oriented PHP?

Object Oriented PHP is a way to take advantage of the new features of PHP. It allows you to make variables and classes that can be used over and over without having to type it all out again. So, mainly, it makes the development process faster and cleaner.

The Basics

We are going to cover the basic functions of OO PHP. We will learn how to make a class, and connect to a database whenever the class is called, and finally we will learn how to call the function.

First, lets to create our class. Let's create a new blank PHP file. We now are going to create our class. We are just going to name it tutorial. Also note there is no closing PHP tag. When working with a fully PHP document it is bad practice to close it.

<?php
class tutorial {
}

Creating the Variables

Now we are going to define 5 variables, I know it seems like a lot but trust me, its not. I'll write the code then explain the little tags.

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
}

The variables look a lot like the usual PHP variables, but now they have private, public or protected in front of them. Here is what each means...

  • Public - variables labeled with this are visible to all classes.
  • Private - variables labeled with this are only visible to its own class.
  • Protected - variables labeled with this are visible by only its own class and subclasses.

The __construct Function

When you are working on a class, there are two functions you never have to call. One is the __construct method. The __construct function will run when the class is called, so you will not have to manually call the function. We are going to make it so it automatically connects to our MySQL database when we call the class.

Now we open up our function...

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
function __construct(){
}
}

Anything we write between those to brackets will now be called and ran when the class is called. Let's now create the connection...

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
function __construct(){
$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die(mysql_error());
}
}

Now it works! If you filled out the information in the variables it will work and connect to the database. You won't have to worry about it again in the document. Also notice that when you call the variable you put $this->var, it’s just the way you have to do it. Also remember that after it points to the variable do NOT put a $. But lets check that it connects and if it doesn't lets show the error.

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
function __construct(){
if($this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die(mysql_error())){
echp "Connected to Database";
}
}
}

Finally, The __destruct Function

The __destruct function runs when everything is done running and "shutting down". It does not need to be called along with the __construct function. For this tutorial we are just going to close the MySQL connection. This is quite simple really.

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
function __construct(){
$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die(mysql_error())
}
function __destruct(){
//Close the Connection
$this->mysql->close();
}
}

Save this file as 'class.php'.

Our Final Class Code

<?php
class tutorial {
public $mysql;
private $db_host = 'localhost'; //Most Likely localhost
private $db_username = 'username'; //Your username
private $db_password = 'password'; //Your password
private $db_name = 'database_name'; // Database Name
function __construct(){
//Start the Connection
$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name)
or die(mysql_error());
}
function __destruct(){
//Close the Connection
$this->mysql->close();
}
}

Calling the Class

All we have yet to do is call the class. Make a new PHP file and at the top of the document open PHP tags.

<?php
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>

Now inside the tags we are going to require the class file and create a new variable called tutorial. The variable will call the function.

<?php
require('class.php');
$tutorial = new tutorial();
//To call a function you can do it like this...
//$tutorial->functionName();
//This can be placed anywhere in the document.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>

A Real World Example

Now, to show why you should use Object Oriented PHP, let’s make a simple twitter script that will retrieve your latest tweet. This will show why it is easier how much faster it is when using Object oriented PHP. So first, we need to make our basic class and function.

<?php
class twitter {
public username = 'kr3wsk8r231'; //Your username here
public amount = '1';
function latest(){
}
}

Alright, that looks good. You will notice we have a class called twitter, variables named username and amount, and a function called latest. The variable you need to fill out with the username you want the latest tweet from. You can also fill out the amount you want.

Now I am going to write a bit more code, then I will explain it.

<?php
class twitter {
public $twitter_base = 'http://twitter.com/statuses';
public $twitter_username = 'kr3wsk8r231'; //Your username here
function latest(){       
$url = "$this->twitter_base/user_timeline/$this->twitter_username.xml?count=1";
$content = file_get_contents($url);
$xml = new SimpleXMLElement($content);
$status_item = $xml->status;
$status =  $status_item->text;
return $status;
}
}

So, what I did was got the twitter url and set the variables in place of the username and amount so it was not hardcoded and easier to change. Then we assigned the returned values of $url to $content. We then sent $content thought a few filters and finally returned the content to display it. The only thing we have left to do is make a new PHP page and call the function.

You should have saved your class file, I saved mine as twitter.php. We now need to require the class, call it and set it to a variable then call the latest function.

<?php
require('twitter.php');
$twitter = new twitter();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php echo $twitter->latest(); ?>
</body>
</html>

There, we called the class, defined it to the variable $twitter then finally echo it out into the body (To keep everything valid). So, did it work? Yup, you should now see your latest tweet display.

Q&A

How was that faster?

Well think of it like this. If you want to display it twice on your page would you rather type that all out again or only type <?php echo $twitter->latest; ?>? I know that it is a lot less hassle.

I'm Still not sure out all this.

Most people are not at first. They tend to think it is a waste to create more than one file. But once you start to get used to it, you understand how much time you really save.

Is it used often?

Yes, Object Oriented PHP is being used more frequently each day. Developers like me and you are realizing how much time they save by writing their code a little differently.

Other Examples

Basic Login System - By Jeffery Way

Login System

Jerry Way has a awesome tutorial on how to make a simple login system. It uses OO PHP. Check it Out. It will teach you how to create a fully working user registration system and page protection.

Online File Storage - Antti Sand

File Storage

Learn how to create a online file storage script. Just select the file you want to upload and there you go! This is mostly written in OO PHP with classes and functions.

How to Paginate Data - Jason

Paginate

Learn how to simply get data from the database and paginate it! This can be very useful if you have thousands of results!

Final Thoughts

So, what we have learned? We learned that Object Oriented PHP is a lot more useful then at first thought. It really helps the development process go faster than usual. I hope you enjoyed this tutorial. Please post any questions throught the comments and I will be sure to answer them. See Ya!

5 Comments

  1. Gaby July 19, 2009
  2. Cody July 19, 2009
  3. Zach Dunn July 26, 2009
  4. Cody Robertson July 26, 2009
  5. Jason September 9, 2009