Fork me on GitHub
RSS
 

PHP Class Tutorial – Part 3 – What Are Class Constructors?

28 Sep

So just what are class constructors, and how can they be used within PHP classes / OOP programming? When a PHP class is first called, the class will automatically run the class constructor function, which can help automatically configure the class. This can be useful if you need to preset some instance variables, sessions or cookies – prior to using the class methods.

PHP Class Tutorial Chapters

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

Starting Point

Let’s follow on from the previous tutorials, so we are using the following code as our starting point for this tutorial. If you don’t want/need to read the previous tutorials, please use the following code as the example for this tutorial.

class Time {

  var $sTime;

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

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
  }
}

Let’s __construct()

Again, to keep things simple, I’ll show a simple implementation of how using class constructors in PHP can help to build more efficient classes. Let’s assume that we want to create a new instance of our Time class, but set a default date without having to run any class methods.

How would we do this? Well we have an instance variable $sTime that we could manipulate off the bat. If we add the following (and I usually add constructors to the top of the class file, just after the instance variables have been declared – for readability – nothing else):

  function __construct(){
    $this->GenerateCurrentTime();
  }

(NOTE: We’re adding this just after the var $sTime; line). Then as soon as we declare a new Time class, using:

$oTime = new Time();

The class method GenerateCurrentTime() would be executed immediately. This means that we can instantly get a meaningful result from our instance variable, $sTime. So if we were to run the following:

$oTime = new Time();
echo $oTime->sTime;

We’d see the current time displayed on the page – without having to manually run any class methods. This example is basically a shorthand way of doing:

$oTime = new Time();
$oTime->GenerateCurrentTime();
echo $oTime->sTime;

So you can see how we’re cutting corners already!

Can You Pass Parameters to Class Constructors?

You certainly can my friends! Let’s say we wanted to preset the date when we first declare the class. This might not seem that useful right now, but down the line we could use the preset date and perform certain calculations on it, such as getting the days between the preset date and the current date. For the purposes of this tutorial, I’ll demonstrate how we can set an optional preset date. If we don’t set a preset date – the date will be set to the current date. Following me? Good! :-P

Let’s modify our __constructor() class to the following:

  function __construct($sPresetDate = false){
    if($sPresetDate){
      $this->sTime = $sPresetDate;
    }else{
      $this->GenerateCurrentTime();
    }
  }

Now, we can declare our class in one of two ways:

$oTime = new Time(date('Y-m-d H:i:s'));
echo $oTime->sTime;

Or…

$oTime = new Time();
echo $oTime->sTime;

Both would return the same date and time (if executed at the same time for you pedantic people!) but it demonstrates how you can pass parameters to class constructors.

Complete Code

Out complete, with the class constructor would now look like the following:

class Time {

  var $sTime;

  function __construct($sPresetDate = false){
    if($sPresetDate){
      $this->sTime = $sPresetDate;
    }else{
      $this->GenerateCurrentTime();
    }
  }

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

  function ShowFutureDate($iAddDays=0){
    $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days"));
  }
}

Nice! It looks like our class is coming along well. We’ve now covered the basics, what $this-> means and what class constructors are.

PHP Class Tutorial Chapters

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

 
44 Comments

Posted in PHP

 

Tags: , , ,

Leave a Reply

 

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

    September 28, 2010 at 8:44 pm

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

     
  2. PHP Class Tutorial | edrackham

    September 28, 2010 at 8:46 pm

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

     
  3. PHP Class Tutorial – Part 3 – What Are Class Constructors? | All Beginner Tutorials

    September 28, 2010 at 9:05 pm

    [...] need to preset some instance variables, sessions or cookies – prior to using the class methods. View Tutorial Class Constructors, OOP Tutorial, PHP [...]

     
  4. jehnee

    October 30, 2010 at 4:01 pm

    thanks mate! very helpful

     
  5. G Natararajan, Abgel Breeze Pure

    November 21, 2010 at 7:35 pm

    I am grateful tht the example shown has been developed from very simple well known script to catch the complexities involves in a manner so simple that , there hasbeen NO better way to make my brother easily understand it. I failed earlier to make him get classes in PHP fast as he did now, after reading youeexamples

    Nallicherry Natarajan Angel Breeze Pure
    Mandavelippakkkam

     
  6. G Natarajan, Abgel Breeze Pure

    November 21, 2010 at 7:37 pm

    am grateful tht the example shown has been developed from very simple well known script to catch the complexities involves in a manner so simple that , there hasbeen NO better way to make my brother easily understand it. I failed earlier to make him get classes in PHP fast as he did now, after reading your examples

    Nallicherry Natarajan Angel Breeze Pure
    Mandavelippakkkam

    Reply

     
  7. Isaac Atuta

    December 19, 2010 at 6:59 pm

    Perfect. It was kul approach to the crazy php classes

     
  8. Ramanakumar Shankar

    December 28, 2010 at 8:55 am

    Thanks a lot.. Best website I’ve seen for PHP classes…. Am a PHP amateur, with zero knowledge on classes, and after seeing this, I think I can move to some more advanced tutorials…
    Thanks..

     
  9. Ishtiaque

    February 9, 2011 at 12:02 am

    greate work, please check web designing company website.

     
    • flavius

      October 6, 2012 at 4:59 pm

      stop spamming. your websites are pure crap and most of them are stolen templates which you successfully uglified.

       
  10. Emir M

    February 9, 2011 at 6:32 pm

    Very neat tutorials mashallah.

    Just got into OOPHP and been sniffing around tutorial sites with confusion till i stumbled across this one. Its starting to make sense now!

    Thanks alot, keep us updated “friend.”

    E.M.

     
  11. dr4g0n

    February 11, 2011 at 2:02 am

    excellent…

     
  12. Brent

    February 16, 2011 at 3:38 pm

    I’d like to expand upon my question that I placed in Part 2.

    It looks like the constructor is returning it’s results to sTime.

    We now have one constructor and two functions returning results to that variable. If I call ” 1. echo $oTime->sTime; ” , how do I know where the result is coming from?

    Thanks

     
  13. Will

    March 3, 2011 at 7:22 am

    It is a very helpful PHP Class tutorial for beginner. Thanks!

     
  14. matttrach

    March 10, 2011 at 5:12 pm

    While creating the __construct function you set the $sPresetDate = false, why?
    Is this a way of declaring the $sPresetDate variable?
    If so, why not declare that variable in the same place as $sTime ?

     
    • bapu

      May 5, 2013 at 11:11 pm

      that’s a default value, it’s better coding this way

       
  15. Broken Arrow

    March 14, 2011 at 6:11 pm

    Hi,

    Thank you so much for such a nice, short and efficient $PHP->Class(); tutorial ;)

    Regards,

    Joy

     
  16. @kentheone

    April 2, 2011 at 11:13 pm

    Mattrach preset date is set to false so that the second part of the code(else{$this->generateTime();}) is excecuted by default ie when you dont do this
    $oTime = new Time(date(‘Y-m-d H:i:s’)) it executes $this->time =$presetdate.
    The following code works the same way and presetdate is true. Do you understand why?

    function __construct($presetdate = true){
    if(!$presetdate){
    $this->time = $presetdate;
    }
    else
    {
    $this->generateTime();
    }
    }

     
  17. Michael

    April 21, 2011 at 11:15 am

    Good stuff. I’m a newbie to PHP classes too and this sharpened up my knowledge.

    The eureka moment came when you described how the variables can be created inside one class function and the page that calls the class function can then later reference a set of variables created inside the class, without the calling page needing to set them out of a $return.

    Then automatically running a construct sounds really handy. Until now, I couldn’t understand the point of a class as opposed to just a page of functions.

    The next thing I want to understand is how to use classes, includes and functions in the most efficient way.

     
  18. Best naturals

    October 18, 2011 at 9:54 am

    You will be missed.The one place where as a venue and fan I could search by
    what ever perimeters I chose .Good Luck with your future endeavors.

     
  19. cordignator

    November 16, 2011 at 10:13 am

    nice one…..

     
  20. Andres Santillan

    November 17, 2011 at 5:08 pm

    Man so grateful I found this great tutorial, I’ve been working with just functions but no classes and all my code is a mess. Thanks for taking the time to write such an awesome tutorial.

     
  21. Zeeshan Umar

    November 28, 2011 at 5:55 pm

    Really useful tutorial, it is simple and easy to understand

     
  22. bali villa | SLA

    January 3, 2012 at 7:24 pm

    im newbie in PHP and specially PHP Class. i think, this tutorial is good point to start to learn.
    thank you mate, keep good work.

     
  23. Raihan Taher

    May 6, 2012 at 5:50 am

    Thanks it was easy learning..

     
  24. Luke Peters

    May 8, 2012 at 12:00 am

    Hey man, thanks a lot for this tutorial! Very easy to understand, I feel like I finally grasp the concept and functionality of classes. Thanks again!

     
  25. archer

    May 23, 2012 at 6:57 am

    thanks for putting this tutorial up! easy to understand!

     
  26. Sharif

    August 3, 2012 at 8:37 am

    Nice tutorial. I want to add or multiply two number using php constructor. Do you give some idea about this. Anyway my site
    tutphp.blogspot.com

     
  27. Zachary

    October 19, 2012 at 6:55 pm

    Seriously, great job. I’ve read countless other explanations of OOP/classes and still felt confused. After looking through this example I had a serious ‘ah-ha!’ moment and get it. Period. Not only do I now understand classes, but “MVC” suddenly makes sense, too. There are practically no programmers who can step out of their knowledge and explain concisely what this is all about. Now that I understand the class … the model, I get what the view (the web page) and the controller (passing the inputs to the model) do as well. Thanks. :)

     
  28. MTSzabo

    November 28, 2012 at 1:56 pm

    Just FYI:
    Something on this page is crashing IE and Chrome. I had to use Opera to get it to work…

     
  29. Laurince G. Quijano

    December 13, 2012 at 3:47 am

    thanks for the tutorial . it is easy to understand what are the step in PHP regarding Object Oriented.. :)

     
  30. Bhuvan

    January 29, 2013 at 2:03 am

    This is very Simple Good and easy to understand example.

    Thanks

     
  31. test website

    March 17, 2013 at 2:44 pm

    I have noticed that service fees for on-line degree authorities tend to be a terrific value. For example a full Bachelors Degree in Communication in the University of Phoenix Online consists of 60 credits with $515/credit or $30,900. Also American Intercontinental University Online provides a Bachelors of Business Administration with a entire program feature of 180 units and a cost of $30,560. Online studying has made getting your college degree far less difficult because you can easily earn your own degree through the comfort of your home and when you finish working. Thanks for all the other tips I have learned through your web site.

     
  32. Chris

    May 8, 2013 at 6:26 pm

    I’m currently transferring all of my script-style PHP files for a web application over to a more OO design. Coming from a scripting background, these tutorials were awesome. Thanks!

     
  33. Mahendra

    May 30, 2013 at 4:38 pm

    Nice one … love it..

     
  34. Sushathachi

    July 13, 2013 at 6:20 am

    Excellent ! Very easy to remember

     
  35. tariq

    July 30, 2013 at 1:27 pm

    thanks for writing such article thanks again!

     
  36. John Porritt

    July 31, 2013 at 1:38 pm

    Brilliant Tutorial! Has made me understand so much more about PHP compaired to other websites I have looked at! Great job!

     
  37. Jay

    August 7, 2013 at 3:25 pm

    Thanks! As so many people have already stated, this example is simple and easy to understand!

     
  38. vinay

    August 12, 2013 at 9:30 pm

    Hi.. Really great tutorials..
    but what about the other parts.. (part 4.. etc). pls let me know..

     
  39. sigmato

    October 22, 2013 at 3:14 pm

    I was wondering what constructor was? This tutorial mad me easy to understand.

     
  40. television rules the nation around the world

    February 10, 2014 at 4:57 am

    Please let me know if you’re looking for a article author for your weblog.
    You have some really great articles and I believe I would be a
    good asset. If you ever want to take some of the load off, I’d love to write some
    content for your blog in exchange for a link back to mine.
    Please send me an e-mail if interested. Kudos!

     
  41. flyer printing roodepoort

    March 31, 2014 at 4:44 am

    It’s very easy to find out any topic on net as compared to textbooks, as I
    found this post at this website.

     
  42. Printersgoldcoast.net

    March 31, 2014 at 8:17 am

    Excellent weblog here! Also your web site loads up fast!

    What host are you the use of? Can I get your affiliate hyperlink on your
    host? I want my website loaded up as quickly as yours lol