Fork me on GitHub
RSS
 

PHP Class Tutorial

09 Feb

Easy to follow PHP class tutorial (which is Object Orientated Programming – OOP). I’m not sure how to start this one… It can be quite difficult to understand PHP classes at first, but hopefully I’ll make everything seem easy! Let’s just get stuck in shall we…

Update! Shameless, shameless plug…

I’ve made a free iPhone app (What Should I Make For Dinner Tonight?) and was wondering if you would be interested in the source / helping me to improve this app.

PHP Class Tutorial Chapters

Part 1 – Jumping In With Two Feet
Part 2 – What does $this-> mean in a PHP class file?
Part 3 – What Are Class Constructors?

Brief overview…

Ok so you’re actually reading this php class tutorial overview? You must be serious about learning how to create and use PHP classes…

Firstly, when you hear someone talking about PHP with Object Orientated Programming, or OOP as it’s otherwise known, they are in-fact referring to PHP classes. PHP classes can be used to group together a set of ‘like’ functions used within a bigger application. Their main advantage is the fact that you can edit the particular class function, or functions and make a site-wide change. Classes also help give you a more structured approach to programming, and those that like to hack with some GPL released web applications (with PHP classes) will have a much better understanding of the workings of them.

This may not be the best example of explaining why to use classes in PHP, but it’s an example of how to use them.

To begin our PHP class tutorial, let’s start by creating a new file called time.php. Within this file, let’s add some simple code (this isn’t a PHP class yet!):

$sTime = gmdate("d-m-Y H:i:s");
print 'The time is: ' . $sTime;

This will simply assign the current date and time to the variable $sTime and then print the string ‘The time is’ with the variable value at the end (e.g. The time is: 09-02-2007 21:42:28).

How would we do this, using a class? Well there’s many ways, however I would recommend using the class file to generate the time, then use the acutal ‘action page’ (time.php) to output the time. Let’s create our class file!

Get in class!

So, now we’re going to make the above into a function, which will be placed inside our new PHP class file, for future use. Create a new file (keep it in the same directory for this tutorial). Let’s call it class.Time.php. Add the following code:

class Time {
  function GenerateCurrentTime(){
    $sTime = gmdate("d-m-Y H:i:s");
    return $sTime;
  }
}

Lets do this line by line… The first line, class Time {,declares the class as open (exactly the same as a function in PHP, but without the brackets in this case). This tells PHP that we have a new class, and we’re calling it ‘Time’.

The next line declares a new function. The difference here is that it exists ONLY within the scope of the class (e.g. it’s built WITHIN the PHP class). We then generate the time as we did before, assigning it to the variable $sTime and then return the value of this variable. The function then closes, followed by the class closure (the squiggly brackets ‘}’, or “close-stache”). Note that our class needs to also be wrapped in PHP tags (<?php … ?>).

Now open the original file, time.php, and change the code to match the following:

include ('class.Time.php');
$oTime = new Time;
$sTime = $oTime->GenerateCurrentTime();
print 'The time is: ' . $sTime;

Now, the first line here includes the time PHP class file (include (‘class.Time.php’);). We must include all the PHP class files we wish to take advantage of, otherwise how the hell would PHP know about these files?

The next line, $oTime = new Time, creates the class object and stores it in the variable $oTime. Notice, to store the class in an object variable, we use VARIABLE = NEW CLASSNAME. VARIABLE can be anything, then there must be an equals sign ‘=’. NEW must use ‘new’ or ‘&new’, and the CLASSNAME must match the name of the class. In this case, the name of the class is Time (case sensitive – as PHP is throughout). The PHP class name is ‘Time’ because we created the class using class Time {.

If we had used class HelloWorld {, as you can guess, the PHP class name would be ‘HelloWorld’.

Anyway… now we’ve created our class, we have also included it within the page we want to make use of it. Not only that, we have ALSO initalised our class by defining it in an object variable – $oTime. Now, it’s not completely covered within in the scope of this PHP class tutorial, but you can kind-of think of $oTime being a variable which stores functions that we can do many things with.

So, the next line:

$sTime = $oTime->GenerateCurrentTime();

This simply assings the variable $sTime with the result of the function GenerateCurrentTime() within the Time class. How does it do this? Simple… We want to use the function GenerateCurrentTime() within the class $oTime so we simply us:

$oTime->GenerateCurrentTime()

This tells PHP exactly what we want to do. The ‘->’ explains to PHP that the prefix (in this case $oTime, which we know holds the class object) is the parent of the latter (again, in this case the latter is GenerateCurrentTime()). So it basically means, run GenerateCurrentTime() within the $oTime class. Thus assigning whatever is returned by the function GenerateCurrentTime() to the variable $sTime.

The last line does what we did from scratch… print out the results with the prefixed string ‘The time is’.

In the next PHP class tutorial installment, we will discuss what $this-> means, and how it can be immensely beneficial to you to use PHP classes!

PHP Class Tutorial Chapters

Part 1 – Jumping In With Two Feet
Part 2 – What does $this-> mean in a PHP class file?
Part 3 – What Are Class Constructors?

 
53 Comments

Posted in PHP

 

Tags: , , , ,

Leave a Reply

 

 
  1. Marea

    October 18, 2008 at 2:06 pm

    As a newbie to OOP your class tutorial is very easy to follow and I am waiting for your next tutorial on $this.
    Regards
    Marea

     
  2. Robin

    February 9, 2009 at 10:00 am

    Well I’m looking forward to the next php class tutorial. I came this far before but when you use several functions and error handling in 1 class, it becomes a nasty trick ;)

     
  3. Arifur Rahman

    March 31, 2009 at 2:07 pm

    I know little php. You tutorial on php OOP help me very much. Keep in touch. Thank you vary much.

     
  4. Helen Hunt

    June 19, 2009 at 2:19 pm

    I have been using Java for some time now and was wondering how PHP class or object relate to Java.

    Does it follow the same OOP approach that is used in other languages?

     
  5. Noel Pulis

    August 30, 2009 at 6:12 pm

    Thanks for the tutorial, it help me a lot.

     
  6. Still why

    September 9, 2009 at 4:44 pm

    GenerateCurrentTime();
    print ‘The time is: ‘ . $sTime;

    //or just this
    print ‘The time is: ‘ . gmdate(“d-m-Y H:i:s”);

    ?>

     
  7. Helen Hunt

    October 20, 2009 at 11:52 am

    I have found your tutorial so simple to follow that in the last couple of weeks, I’ve been working my way through a copy of PHP book I got at the local library.

    Thanks for the tutorial :)

     
  8. Peter

    December 20, 2009 at 3:08 pm

    Thanks very much for the valuable TUT.. Still rocking TUT are available ;)

     
  9. Brandon

    January 7, 2010 at 7:42 pm

    Thank you for breaking down just the basics on php classes. This is exactly what I needed.

     
  10. rehabilitasyon

    July 8, 2010 at 4:30 pm

    good php saol

     
  11. Awais Anis

    July 29, 2010 at 12:16 pm

    good basic example of class is provided!!!

     
  12. desis

    August 30, 2010 at 3:58 am

    I am new in OOP .. this is very nice one to follow

     
  13. PHP Class Tutorial – Part 2 – What is $this-> | edrackham

    September 16, 2010 at 8:29 pm

    [...] make sure you’ve followed my first PHP Class Tutorial before starting this one, as it follows on using the previous example. This tutorial will explain [...]

     
  14. PHP Class Tutorial – Part 3 – What Are Class Constructors? | edrackham

    September 28, 2010 at 8:39 pm

    [...] Part 1 – Jumping In With Two Feet Part 2 – What is $this-> Part 3 – What Are Class Constructors? [...]

     
  15. Erin

    October 12, 2010 at 3:53 pm

    This tutorial is fantastic for someone just getting into OOP in PHP. Thank you so much for the lesson!

     
  16. hygsan

    November 25, 2010 at 4:48 am

    thanks for the lesson :)
    now i know, i should learn OOP!!!
    i’ll never “re-invent the wheel” again!!! =))

     
  17. Frank

    November 28, 2010 at 2:19 am

    This is excellent!
    Thank you very much!

     
  18. dr4g0n

    February 10, 2011 at 9:36 am

    wonderful…

     
  19. Christo Fouche

    May 2, 2011 at 4:51 pm

    Thank you for this Tutorial. I like the easy way in which you explain everything.

     
  20. jozaf

    June 28, 2011 at 8:51 am

    really a good tutorial for beginner

     
  21. jozaf

    June 28, 2011 at 8:56 am

    really a good tutorial for beginner guinness

     
  22. ronald

    August 18, 2011 at 7:51 pm

    thanks for the tutorial. very easy to follow.

     
  23. www.coupondiscounts.us

    October 3, 2011 at 3:38 pm

    It is a perfect turorial for beginers like me.

     
  24. Best naturals

    October 18, 2011 at 9:24 am

    Thanks for your many years of a great service well done! I’ve always felt good
    about listing my concerts with you and linking from my website.

     
  25. gtwebworx

    October 25, 2011 at 3:17 am

    very helpful to all newbies in php oop…keep posting related tutorials coz I’m following. :-)

     
  26. ahmad balavipour

    October 29, 2011 at 5:57 am

    Thanks alot, very good tutorial

     
  27. csColeman

    November 21, 2011 at 12:29 pm

    Bravo! It was time to review with a much better grasp on using classes, and your explanations and examples have made this tutorial just the thing that I was looking for. Thanks again, keep up the good work!

     
  28. Raihan Taher

    May 5, 2012 at 5:47 am

    Thanks for such a nice post. My fear of OOP is now going away.. But is it necessary to name a class file,

    class.Time.php

    or it can be just

    Time.php

    Thanks

     
    • Ed

      June 28, 2012 at 11:54 am

      Hello,

      You can call the class file anything you like!

      Ed.

       
  29. Dj

    August 20, 2012 at 7:39 am

    Note that our class needs to also be wrapped in PHP tags ().

    Can anyone explain me this line?

     
  30. Bonnes pratiques PHP | My Blog Notes

    August 30, 2012 at 9:38 pm

    [...] PHP Class Tutorial : http://edrackham.com/php/php-class-tutorial/ [...]

     
  31. James59

    October 27, 2012 at 4:36 am

    Great site. Just completed the video tutorials from http://learnphpquick.com/ Its all going good

     
  32. Jacob

    November 19, 2012 at 1:48 pm

    I’ve avoided OOP as much as possible, but I can see why it’s handy. Great tutotial, thanks.

     
  33. lattimore

    November 30, 2012 at 8:29 am

    Simple but detailed.

     
  34. Milad

    December 5, 2012 at 4:29 am

    Beautiful illustration.
    Keep on doing great job,

     
  35. Najla

    December 28, 2012 at 5:12 am

    thanks for your tutorial.. very helpful.. :)

     
  36. Ateeq

    January 26, 2013 at 10:36 am

    hmmmm good bro

     
  37. Usman Ghani

    March 5, 2013 at 7:01 am

    Good and easy article. helps alot in concept of class. :)

     
  38. Darryl

    April 24, 2013 at 6:11 pm

    Wow, such an awesome tut on the fundementals of classes in php. So simple and easy to follow.

     
    • sachin

      May 28, 2013 at 8:43 am

      ya its so simple….
      You don’t know before yet??

       
  39. mobiltelefoner

    April 26, 2013 at 8:29 pm

    I blog frequently and I genuinely appreciate your information.

    This article has really peaked my interest. I will take a note of your blog and
    keep checking for new information about once per week.

    I opted in for your Feed too.

     
  40. sachin

    May 28, 2013 at 8:41 am

    fs

     
  41. Mahendra

    May 30, 2013 at 12:41 pm

    Very nice tutorial… I Simply understood the class concept ..
    Thanks a lot..!!!

     
  42. Fortune Consultants & Co

    July 16, 2013 at 11:33 am

    Thats it i reslly need this Tutorial, thanks you for greate examples and tutorial,
    FORTUNE Consultants & Co

     
  43. Jarod

    August 3, 2013 at 5:27 pm

    I followed your tutorial and it worked perfectly up until I removed the line returning the value. Then I stopped getting any dates printed out. Could it be my host?

     
  44. Expert

    August 7, 2013 at 8:06 am

    What is this? You can find better one in http://php.net/manual/en/language.oop5.php, Just waste a web page for bullish.

     
    • Ed

      August 7, 2013 at 8:42 am

      Thanks for your helpful comment. Yes, I’m sure people researching PHP Class tutorials are aware of the vanilla PHP tutorial, but many prefer a less-robotic way of explaining things.

       
  45. Expert

    August 7, 2013 at 8:08 am

    I think all the comments are done by yourself or your friends. Wonder lot of comments for nothing???###@@

     
    • Ed

      August 7, 2013 at 8:43 am

      Has this PHP Class Tutorial upset you in anyway?

       
  46. rahber

    September 7, 2013 at 12:25 pm

    its so conceptual the way you ellaborated..thanks

     
  47. Zobo

    November 10, 2013 at 8:21 am

    This is just the a b c of classes. Thanks . Class in PHP is now clear

     
  48. Laurens

    April 1, 2014 at 6:57 am

    Thank you really much for this tutorial !
    It helped me A LOT !!

    Regards
    Laurens