An Introduction to Object Oriented PHP – Part 2

Introduction
Welcome to Part 2 of a three part series introducing Object Oriented PHP! This tutorial will build off the first part from last week. Compare this to playing a sport; if you don’t know the basics, you’ll never progress.
In This Tutorial
Today, we are going to learn the following:
- Constructors and Destructors
- Returning data from your functions
- Keeping organized
Constructors and Destructors
Think of PHP constructors and destructors like a building. You construct a building at first, then when you’re done using it, you destruct it. Except in PHP, there are no live explosives for the destruction. Let’s look at the following example of constructors:
<?php
class MyClass
{
function __construct()
{
echo "MyClass Loaded!";
}
}
$MyClass = new MyClass();
?>In this example, we create a new class simply called MyClass, then a constructor function that says MyClass Loaded!. Basically, anything you want to happen when you call upon your class, should go in the constructor function.
In PHP, you don’t need to worry about always having a __destruct() method in your class, as all classes and variables are removed after your object is destroyed. (At the end of execution).
Returning data from your functions
In the real world, you don’t want to be using echo statements within your functions, you want to run your function and return the data for you to echo out where you want it. Let’s take a look at the following example that could be part of a blog application:
<?php
class MyClass
{
var $mysqli;
function __construct()
{
$this->mysqli = new mysqli('localhost', 'root', '', 'blog');
}
function get_latest_posts()
{
//Do some database selection
$query = "SELECT * FROM `posts` ORDER BY `id` DESC";
$result = $this->mysqli->query($query);
return $result;
}
}
php?>Here, we are using a constructor to make a new MySQLi connection, and then using that connection set in the constructor to run a possible query, then to return the result set to be used however you’d like to display the data. Simple, right?
Keeping Organized
In the first part of this series, I described classes as boxes, and functions as the things within the boxes. This picture is a great representation of keeping your classes well separated from each other, and their contents nicely arranged.
One key aspect of writing classes is to keep things easy to read and edit later. Let’s take a look at a file from the very popular blogging platform WordPress. As you can see, above every variable declaration, class declaration, and function declaration, there is vital information about the parameters, what the function does, and what it returns. Let’s write our own example now:
<?php
/*
* @name MyClass
* @params none
* Our database class that makes a new database connection, and will insert userdata.
*/
class MyClass
{
/*
* MySQLi Connection Link
*/
private $mysqli;
/*
* __construct
* Sets new MySQLi Connection
*/
function __construct()
{
$this->mysqli = new mysqli('localhost', 'root', '', 'buildinternet');
}
/*
* insert_userdata
* @params username, password
* @returns bool
*/
function insert_userdata($username, $password)
{
//Insert the userdata into the database
if(success)
{
return true;
} else {
return false;
}
}
}
php?>Here, we have said what our class is, what it does, and then defined each function or variable within it. In the insert_userdata() function, we have said what the parameters are and what it returns above the function. As you can already see, these comments help immensely when trying to read your code or trying to find a problem with your code.
Conclusion
Now, after reading the second part in this series, we have all the skills we need to write our MySQLi Database interaction class in Part 3! Thanks for reading and be sure to check back for the third part!















Discussion
July 23rd, 2009 at 6:29 PM
Anxiously awaiting third part :)
Also is there supposed to be anything written above:
” //Insert the userdata into the database”
Or is just assuming that we know how to insert that into w/e database we are using for our specific app.
thanks again, good series to teach correct fundamentals.
July 23rd, 2009 at 7:17 PM
No, I meant to leave it like that, I’m assuming you know how to insert something into a database. :)
Thanks for the comment!
.-= Dixon Crews´s last blog ..dixoncrews: @thecreativeone I think he meant the fact that it was blocked in the US. =-.
July 24th, 2009 at 9:34 AM
Nice article.
.-= Rubens Mariuzzo´s last blog ..Utiliza las fuentes que quieras con TypeSelect =-.
July 24th, 2009 at 11:34 AM
Minor syntactical typo where: if (success). Should be if ($success).
.-= Tommy M´s last blog ..The feed you requested could not be found =-.
July 24th, 2009 at 11:52 AM
@Tommy – I was just saying if whatever query you ran was successful, I was assuming you know how to get to that step.
July 24th, 2009 at 1:37 PM
Sorry for the basic questions…
Do you put the database connection into the constructor so that if there are multiple functions, they can all access that? Is it not a good idea then to put that right into the function?
Lastly, I am not getting why variables like private $mysqli; don’t go in the constructor?
July 24th, 2009 at 1:48 PM
@Randy – Yes, it’s a good idea to do that in the constructor, because declaring it in every function (especially if you have a lot), gets quite repetitive.
Also, the $mysqli variable is a class variable, that can be accessed throughout the class, so you have to declare it at the top.
.-= Dixon Crews´s last blog ..dixoncrews: @thecreativeone I think he meant the fact that it was blocked in the US. =-.
July 24th, 2009 at 2:32 PM
Nice article. Impressive for someone of your age. But it would make more sense to have the database connection info passed into the object on construction. Allowing you to create a class that would work without having to change the connection info thats hard coded into it. It would also be sensible to call this information from a seperate file. But thats probably beyond the scope of an introduction series.
Anyways keep up the good work.
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.