An Introduction to OOP in PHP

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    An Introduction to OOP in PHP

    Okay, show of hands out there - who else is tired of the boring old car analogies when it comes to talking about object-oriented programming in PHP? I have to admit; even I got a little sick of reading them after a bit. It seemed like there wasn't much originality behind them, and several of them just assumed that you understood what "$this->car_name" was.

    So, here we go with something a little bit different - hopefully it'll turn out to be something useful for all of you developers out there trying to wade through the wide world of object-oriented programming with PHP.

    What's so cool about OOP anyway?
    Well, let's start at the beginning and lay down some basic terms to get things started. First off, most PHP developers write when their first coming into the language is called "procedural". In this kind of code, one thing happens after another and the most exciting thing that could happen is the inclusion of another file. Functions are scattered here and there, and a library of them may even be used to help move things along a bit faster. There are limitations to this kind of programming, though. Procedural code tends to get pretty unwieldy pretty quickly when working with larger site. Shifting things around to included files helps, but it doesn't get to the root of the problem.

    Object-oriented programming can help with all of this. Let's back up just a second and talk about what the "object" part in that term means. Objects are variable types in PHP that can do all sorts of fun things. They can be passed around from place to place all while maintaining all of their properties and methods inside. If that doesn't make sense to you yet, hang with me a bit, I'm going to help. The first step is to discover how to create an object of your very own.

    The Object of Our Affections
    Objects are really just a fancy variable type (as mentioned above) with some nifty features that come along with them. To create an object, you'll need something called a class. Think of a class as the framework behind an object that defined the functionality and variables to keep inside. Here's an example:


    PHP Code:
    <?php 
    class myClass 
        function 
    myClass(){     
        } 

    ?>

    In this case, "myClass" is, well, the name of the class and the word "class" is a keyword that PHP looks at to know what you're doing. Right inside the class definition, there's a function, "myClass". Now, I'm not trying to confuse you on purpose - there's a reason why it's named the same as the class. It's a special kind of function called the constructor. Just like laying the foundation and putting up the walls of a new building is part of constructing it, our "myClass" function is run when the object is first created.

    Ah! Now to the fun part! Object creation! (Well, not so much fun as the next step in the process).

    So, we have our little sample class above sitting there, ready to use. But, to be able to get to anything inside it, we need to make an object that represents it. Here's an example:


    PHP Code:
    <?php 
    $mine
    =new myClass(); 
    ?>

    Man that's hard work...well, okay - so it's not, but there's still a little there to explain. The variable "$mine" is the newborn object. If you do a print_r() on it (you do know about print_r, don't you?), you can see that it's a little bit special. To tell PHP that we want to make it an object, we use the "new" keyword along with the name of the class. Our example above doesn't really do anything yet, but that's about to change when we introduce properties.

    Putting Properties Into the Mix
    Like everything else involved with classes, properties are really just something you already know (and love). Properties are just variables in disguise. Why are they different? Well, Inside of a class, you can have variables, but there are some variables that ascribe to a higher calling. These variables can be accessed both inside and outside of the class and are global inside an object. Want an example? Here's a simple one:

    PHP Code:
    <?php 
    class myClass 

        var 
    $my_var 'testing'

        function 
    myClass(){ 
        } 

    $mine=new myClass(); 
    echo 
    $mine->my_var
    ?>

    In our example above, we're using the same class structure as before, but we've added something different. The "$my_var" variable defined at the top puts that value out where we can get to it later. Later comes around when, after creating the object, we have some fun with a new operator entering the game, the "->" (or as I usually call it, the arrow). Basically, this tells PHP that the variable you're referencing is a part of the "$mine" object. PHP automatically pulls the current value from the object and echoes it out just like any other value. And this isn't limited to just variables, either - you can use the arrow to call methods too (functions in a class, remember), like so:


    PHP Code:
    <?php 
    class myClass 
        function 
    myClass(){ 
        } 
        function 
    echoMe(){ 
            echo 
    'me'
        } 

    $mine=new myClass(); 
    $mine->echoMe(); 
    ?>

    Running this script will result in the text "me" being output to the page. Pretty simple, huh?

    Taking the Next Step
    Since we're starting to get a bit more complex anyway, why don't we apply all of this great knowledge that we've already accumulated into something a bit more useful - like a simple graphical example. In this example we're going to create a box on the page (a DIV tag) and with the help of PHP and some CSS, change a few things about it. But first, the code:


    PHP Code:
    <?php 
    class myHappyBox 

        var 
    $box_height 100
        var 
    $box_width 100
        var 
    $box_color '#EC0000'

        function 
    myHappyBox(){ 
        } 

        function 
    setHeight($value){ 
            
    $this->box_height=$value
        } 
        function 
    setWidth($value){ 
            
    $this->box_width=$value
        } 
        function 
    setColor($value){ 
            
    $this->box_color=$value
        } 

        function 
    displayBox(){ 
            echo 
    sprintf(
                <div style="height:%spx;width:%spx;background-color:%s"> </div> 
            '
    ,$this->box_height,$this->box_width,$this->box_color); 
        } 

    $box=new myHappyBox(); 
    $box->displayBox(); 
    ?>


    Now, don't let this code scare you off, it's really not that complex. There's a few new things to look at in here, but nothing that doesn't make sense with the right explanation. We know that we're going to be building a box with this class, so we know that the box is going to have certain properties - height, width, and a color. Looking at the class above, you can see those three settings defined as properties with default values. By defining them there at the top, we have settings to fall back on if we do like the example shows and just call displayBox(). As it stands, the example will show a 100 pixel by 100 pixel DIV with a red background. This is all well and good, but what happens if we want to change one of these settings? Well, that's what the other functions are for.

    There are three "set" functions in our myHappyBox class - one for height, one for width, and one for the background color - and they all work the same basic way. Each of them takes in a value and sets the global (to the object) property to the new value. So, if we wanted to change the size of the box, we could do:


    PHP Code:
    <?php 
    $box
    =new myHappyBox(); 
    $box->setHeight(30); 
    $box->setWidth(300); 
    $box->displayBox(); 
    ?>

    The above code would then alter our default box and display one that's a whole lot wider than it is tall. The same kind of change can be made with the setColor method, giving it a value of an HTML color (hex).

    Wrapping it all up
    So, that's basically it - not really anything to be scared of or to avoid for the future. In fact, object-oriented programming can be one of the better things to happen to you and your code. Sure, rewriting that application you're currently on in a more "OOP fashion" might be a big pain, but there's always the next project to consider. And remember, there's more to working with objects, classes, methods, properties, blah, blah, blah than what I've said here. You should definitely head over to the PHP.net site and check out their great resource on the topic. It has the answers to the questions you'll want to know now that you're finished with this little tutorial.

    Thank you for reading my tutorial....
    Don't forget to thank me please.....
    BakGat
    Code:
    class Counter {
    public:
      void Count();
      int  ReadDisplay();
    private:
      int  CurrentCount;
    };








    Back up my hard drive? How do I put it in reverse?
    My Community
    BakGat
    sigpic

    #2
    Nice..do u Mind mentioning the source or u written it?
    she is beautifull than php.and i love her more than php.
    sigpic

    Comment


      #3
      Same OOP in PHP can use alot of cpu or ram.

      if you coded it in the right way it will be faster then including pages
      Visit: Chat4u.mobi - The New Lay Of being a site of your dreams!
      Visit: WapMasterz Coming Back Soon!
      _______
      SCRIPTS FOR SALE BY SUBZERO
      Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders.
      FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others...
      _______
      Info & Tips
      php.net
      w3schools.com

      Comment


        #4
        Its written but if u google for it you will find more detailed tutorials....
        BakGat
        Code:
        class Counter {
        public:
          void Count();
          int  ReadDisplay();
        private:
          int  CurrentCount;
        };








        Back up my hard drive? How do I put it in reverse?
        My Community
        BakGat
        sigpic

        Comment


          #5
          Ok I added a few e-books... This is what I used to get familiar with OOP it's really a nice way to code as it's easier to maintain your site... No more 1000's of codes in 1 place.... Check it out read through it and get coding....

          OOP STYLE

          [HIDE-THANKS]frankfurt_oop.pdf
          php cook book.pdf
          PHP-Tutorial-Part2-OOP.pdf
          php5.pdf
          tutorial54.pdf
          [/HIDE-THANKS]

          BakGat
          Code:
          class Counter {
          public:
            void Count();
            int  ReadDisplay();
          private:
            int  CurrentCount;
          };








          Back up my hard drive? How do I put it in reverse?
          My Community
          BakGat
          sigpic

          Comment


            #6
            someone ask for the source PHPDeveloper.org: Tutorial: An Introduction to OOP in PHP found it a few years back

            Comment

            Working...
            X