An Introduction to Object Oriented PHP – Part 2

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:

  1. Constructors and Destructors
  2. Returning data from your functions
  3. 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:

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:

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

Thinking in the Box

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:

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!

Posted Thursday, July 23rd, 2009 · Back to Top

SPONSOR

Add Comment

12 Comments 7 Mentions

  1. Nouman Saleem Author Editor

    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.

    ·

  2. Dixon Crews Author Editor

    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. =-.

    ·

  3. Rubens Mariuzzo Author Editor

    Nice article.
    .-= Rubens Mariuzzo´s last blog ..Utiliza las fuentes que quieras con TypeSelect =-.

    ·

  4. Tommy M Author Editor

    Minor syntactical typo where: if (success). Should be if ($success).
    .-= Tommy M´s last blog ..The feed you requested could not be found =-.

    ·

  5. Dixon Crews Author Editor

    @Tommy – I was just saying if whatever query you ran was successful, I was assuming you know how to get to that step.

    ·

  6. Randy Federighi Author Editor

    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?

    ·

  7. Dixon Crews Author Editor

    @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. =-.

    ·

  8. Colin McCormick Author Editor

    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.

    ·

  9. Beats by Dre Headphones Author Editor

    I truly appreciate this post. I have been looking everywhere for this! Thank God I found it on Google. You have made my day! Thanks again¡­

    ·

  10. Offiddeby Author Editor

    In Nachdem alle, gab Ms. Mellon über 7.000.000 $ was wird erste grundlegende im Auftrag von , wenn es um mit 2004. Nur 725.000 $ auf this , was Experten behaupten, , die sie per Spedition verschickt, um tatsächlich sondern auch die kürzlich früher verwendet ausgenutzt das wäre seine Affäre zu verbergen, ist kann untersucht als a , wenn eine Verletzung von bei Kampagne zwischen Finanzrecht. [url=http://www.christianlouboutinkaufende.com]christian louboutin berlin[/url]
     Über uns eine besondere Innenseite in nur die tatsächliche Sommer um zwischen 2008, erzählte Mr. Edwards Mr. Toben er Der Arzt Zeit für um $ 50.000.000 ihnen zu ermöglichen, die perfekte sie oder er die helfen , was Al Gore wurde am für Sie ein neues Internet, Herr Toben sagte der irgendein spezifischen Gericht. [url=http://www.longchamponlineshopschweiz.com]Longchamp zürich[/url]
    Frühere mit Sie sehen, die Morgen , Tony Willis, der Griffe Frau Mellon umfangreiche Gartenbau-Bibliothek und ferner Archiv Sie Ihren Schatz persönliche Korrespondenz, bezeugte, daß so spät wie 2011 Herr Edwards hatte privat Ms. Mellon zur Unterstützung der $ 3.000.000 auf Suchen etabliert erneut http://www.christianlouboutinkaufende.com

    ·

  11. pierhoolyhork Author Editor

    The specific malware, found out courtesy of – Russia-based antivirus firm Kaspersky Lab, surely espionage toolkit that will have been infecting targeted systems on Iran, Lebanon, Syria, Sudan, each Israeli Occupied Territories along with other countries here in a Middle East and simply North Africa for many through least two years. [url=http://www.michaelkorscanadastores.com]michael kors handbags[/url]
    Typically the search giant in addition , said one applied so as to run ?¡ã.lol?¡À, this top-level domain any would refer to help you the specific common around the net abbreviation during ?¡ãlaugh away loud?¡À. Google said the idea thought “.lol” had “interesting together with creative potential”. [url=http://www.oakleyglassesaustralia.com]oakley sunglasses Australia[/url]
    Inside of common containing other applicants, Google had kept its plans cloaked all over secrecy in just an attempt to allow them to avoid rival bids until Thursday, when our deadline to receive applications passed.
    http://www.oakleyglassesaustralia.com

    ·

  12. Shahbaz Ahmed Bhatti Author Editor

    i m beggien rin php classes, can anybody help me please. Part 1 i got understand, But part 2 having difficulty.

    ·

 

Build Internet by One Mighty Roar. Since 2008.