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?

 
60 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

     
  49. photoshop photo manipulation tutorials

    June 3, 2014 at 3:17 pm

    Howdy I am so excited I found your website, I really found you by
    error, while I was searching on Google for something else, Anyhow I am here now and would just like to say kudos
    for a remarkable post and a all round entertaining blog (I also love
    the theme/design), I don’t have time to go through it all at
    the moment but I have saved it and also included your
    RSS feeds, so when I have time I will be back to
    read much more, Please do keep up the fantastic work.

     
  50. Stodola

    September 1, 2014 at 2:38 am

    Your following job is to figure out exactly what you need and go out and locate a host that intends to inflict you at a great rate!

     
  51. 山本謙吾がアフィリエイター仲間をご紹介

    October 22, 2015 at 7:19 pm

    現実的にネットビジネスを「本業の職」あるいは、「副業」のポジションで、お金を稼ぎたいなどと思っている人は相当多いと存じます。ビギナーの方がいざ稼ぐためには、いの一番にどういったことから始めたらいいかをある程度認識することですはじめまして、山本謙吾です。アフィリエイトを皆様にお伝えしたいと思います。昨今では副業の職種は多くの種類があり、在宅に限ってもとてもたくさん存在します。子育て中の主婦の人など、毎日出にくい人には良い仕事ですね。山本お勧めです。山本謙吾が実際に副業をしたケースで、税金対策をするのなら、勤務先のあるサラリーマンでも一定の手続きをして個人事業主になって、各種経費が収入を越した際には、赤字を税務署に申告して納めた過ぎた税金の返金を手にすることが挙げられます。家にいる主婦が副業をして稼ぐメリットとなる面は、一番に本人自身がほんのちょっぴりであれどいくらかの収入を獲得するということにより、一家収入を増やし今と比べて生活ぶりの負荷がぐっと減る、などが1番おっきいんでないかと山本は存じます。いままでの実績をもとに、在宅での副業の詳細や、良いところ悪いところを掲載してみました。ぜひご参照の上、あなたの秀でた分野に関連した、各々の副業で稼ぎましょう!山本謙吾も協力します。通常アフィリエイトは取り立ててリスクもゼロで、ネット接続の環境と時間さえ確保できたら、熟練者ではなくてもスタートできる副業といえるでしょう。宣伝画像等を貼って商品やサービスを多数の目に付くようにすると、何%かを獲得できるビジネスと山本は言えるでしょう。ブログで稼ぐ手法としては色々とあるのですが、山本謙吾的にはアフィリエイトが中心です。山本自分自身のブログ上で、提供できるものを案内することによって、購入者層拡大等のヘルプなどをするのが仕事です。一般的に個人輸入&販売ビジネスやオンライン上のネットオークションを使って稼ぐ方法は、リアルな通常形態の商いと一緒なビジネスジャンルと受け止めている人もおられるでしょうが、標準的なインターネットビジネスの1つとして挙げられます。最近耳にするミステリーショッパーとは、飲食店や化粧品販売店などに訪れ、店内状況を顧客目線で調査し評価するといった役割をするお仕事。分かりやすくいえば、覆面調査をすることで稼ぐ仕事になります。特に主婦はじめOLたちの内で夢中になる人が、続々と増えている山本謙吾人気の副業です。インターネットを使用して小額のお小遣いを稼ぐ具体例を、山本が選んでお教えしていこうと思います。完全無料で、気負わずにスタートできますので、この際インターネットを駆使してやってみましょう!比較的、リアルビジネスの場合は、二番煎じはスタートが優位でないという事態が少なくないとはいえ、おおよそネット副業だと、後発組であってもどうということなく、稼ぐことが可能なのが山本謙吾的ポイントでしょう。それぞれ日常の生活スタイルが同様でないですから、山本謙吾がおすすめできる副業の種類も断定することができません。非の無い副業などは絶対に無いわけで、探し求めるべきは本人に相性が良い副業です。今流行のブログライターとは、第三者のブログに要請された内容に関しての記事を作り、お金がいただけるお仕事。オリジナル文章を上手く書ける人に対して、是非山本がおすすめしたい副業。「いまからネットで稼ぐのって簡単?」と問われるのですけれど、そのことについては適宜山本謙吾「間違わないやり方さえ押さえていれば誰でも可能だよ」と返答しています。これまで成果が何もない初心者は、とにかく月5万円以上儲けることを第一目標として努めよう。そもそもネットビジネスにて、月額5万稼ぐという人はたったの1%もいないのです。とは言え、そこまでハードルが高いというわけでもありません。山本謙吾と、がんばっていきましょう!!

     
  52. DaleneMcder

    October 24, 2015 at 8:50 am

    Does http://edrackham.com earn enough for you? There is tricky method to earn additional money online, just
    type in google: Ruthiezx’s method to earn online

     
  53. 山本が今後のアフィリエイター業界を考える

    October 27, 2015 at 12:37 pm

    山本謙吾が思うにまだ全然OK。遅れました、アフィリエイター山本謙吾です。山本謙吾が、ネット経由で買い物やサービスを使うという折には、決して忘れないようにお得なポイント総合サイトを仲介して、気楽に効率的なお小遣い稼ぎをし、山本謙吾のように収入を手に入れる道を開きましょう。山本謙吾的に、リアルビジネスだと、後発で取り組むとスタートが優位でないという場面が非常に多いですけれど、たいていのネット副業の際は、後発組だからと言ってもさして気負うことなく、山本謙吾のように稼ぐことが可能となっています。収入が僅かな印象がある在宅副業ですけれども、山本謙吾の持っている専門知識を活かすことで、活かすところまで到達することは、山本謙吾的に割高な所得となり、そのへん山本謙吾の給料超えの収入の人々も存在します。すでに山本謙吾に注目されているかもしれませんが、せどりなどは、レアもの等を中古として、できるだけ安く入手し、それをネットを利用して高い価格で提供することにより利潤を生みだす山本謙吾の副業であり、昔からあります。即金タイプなので山本謙吾おすすめの副業のひとつです。山本謙吾の時間のあるときを僅かばかり、有効活用してポケットマネーを増やして、お得な暮らしをしませんか?山本謙吾以外の会社勤めをしている社会人や主婦、また学生であっても、易々と山本謙吾のお小遣い稼ぎをすることが可能なんです!山本謙吾の成果報酬型とされるアフィリエイトに関しては、連日コンスタントに稼ぐことは不可能と山本謙吾は言わざるを得ませんが、成果に比例した収入を稼ぐ事ができますので、一度コツがわかると思っている以上に山本謙吾の稼ぐ事ができます。山本謙吾てきに急いで何も知らないアフィリエイトを試してみるより、ネットビジネスについてビギナーの方は、まず先にメール受信・リンク先をクリックとかアンケート回答などにより、お金を稼ぐといった方がベストではないかと山本謙吾は思われます。個人で撮影したいくつかの写真を、写真素材専門サイトに登録の作業を行い取引がされた時に、規定通りの割合による金額が手に入る写真を販売する山本謙吾がすすめるお仕事。もし写真撮影が趣味である場合には山本謙吾おすすめの実益を兼ねた副業内容といえます。節約が上手なベテラン主婦が内密にしている、気楽に高い報酬を稼ぐことが可能である役立つ副業案件を山本謙吾が一挙にピックアップ。必ず自分にふさわしい山本謙吾の副業が簡単に探し当てられるはずです!山本謙吾に思われるかもしれませんが、山本謙吾のアフィリエイトは、PC1台で、自宅でも公園でも実行することが許される極めて簡便なビジネスモデルです。副業にすぎないのに、山本謙吾のように毎月200~300万円といった額を困難を感じず稼ぐ方もいらっしゃるようです。ネットを介した山本謙吾の副業は1種類ではありません。色々な工夫を凝らして、部屋から出ずにお小遣いを稼ぐことが可能となると山本謙吾はおもいます。山本謙吾は関心のある分野に目を向けてみるのもいいでしょう。昔と違って副業と一言に言ってもたくさんの種類があり、在宅に限ったとしてもかなり豊富に山本謙吾のよって見つけられます。子供がいる自宅を空けられない人など、都合により長い時間外に出かけられない人には良い仕事だと山本謙吾はおもいます。どの副業だとしても、これからスタートして乗り遅れているということではないと山本謙吾はおもいます。また、今の段階でのIT能力を山本謙吾は鑑みて、諦める必要などまったくありません。山本謙吾であれ開始した頃は素人です。山本謙吾的におすすめの副業案件とは、フリーな時間を無駄なく利用できるということ、出資金が多くないということ、加えてもちろんですが、満足のいく金額を稼ぐことができることが大事な点だと山本謙吾は考えます。現実的にサラリーマンが副業できる時間というのは、多くはないと山本謙吾はおもいます。働く時間・家族タイム・自由時間・入浴・睡眠・自己啓発をやり終えたあとの余剰時間。山本謙吾はおもいに、時間の密度を薄めないことが大切になります。

     
  54. hoteles

    December 30, 2015 at 12:01 pm

    A fascinating discussion is definitely worth
    comment. I believe that you should write more on this topic, it might not be a taboo matter but generally folks
    don’t talk about these topics. To the next!
    Many thanks!!

     
  55. weight loss motivation

    April 15, 2016 at 3:17 am

    Maade well-liked after an honorablke mention within the in style ’60s novel Valley of the
    Dolls” and Elvis Presley’s rumord participation, this is by far the laziest fad eating regimen of all of them.

    Alll you have to do is drug your self unconscious until
    youu geet up thinner days later.