Advantages of using classes over functions?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • bissatch@yahoo.co.uk

    #1

    Advantages of using classes over functions?

    Hi,

    Generally if I re-use code, I use a function. If I need to use these
    functions over a number of pages I write the function to an include
    file where all pages have access.

    So when should I ever use PHP classes instead. I have learned how to
    put together PHP classes but never seen a reason to use them where I
    can simply use a function.

    Im basically just wanting to know classes benefits over functions. If
    something can be better put together in a class I would like to be
    doing it that way. Any suggestions?

    Cheers

    Burnsy

  • Jacob Atzen

    #2
    Re: Advantages of using classes over functions?

    On 2005-05-09, bissatch@yahoo. co.uk <bissatch@yahoo .co.uk> wrote:[color=blue]
    > Im basically just wanting to know classes benefits over functions. If
    > something can be better put together in a class I would like to be
    > doing it that way. Any suggestions?[/color]

    What you're asking is why Object Oriented Programming (OOP) is better
    than procedural programming. The answer is: That wholly depends on the
    task at hand. Generally speaking OOP gives you some tools for managing
    complexity in larger systems. It also provides a mean for eaiser reuse
    of existing code. A good example of the power of OOP can be found here:

    <http://www.sitepoint.c om/forums/showthread.php? t=59898#post439 958>

    --
    Cheers,
    - Jacob Atzen

    Comment

    • Kenneth Downs

      #3
      Re: Advantages of using classes over functions?

      bissatch@yahoo. co.uk wrote:
      [color=blue]
      > Hi,
      >
      > Generally if I re-use code, I use a function. If I need to use these
      > functions over a number of pages I write the function to an include
      > file where all pages have access.
      >
      > So when should I ever use PHP classes instead. I have learned how to
      > put together PHP classes but never seen a reason to use them where I
      > can simply use a function.
      >
      > Im basically just wanting to know classes benefits over functions. If
      > something can be better put together in a class I would like to be
      > doing it that way. Any suggestions?
      >[/color]

      This is a matter of opinion. One extreme states the fact that classes give
      you nothing you can't have without them, and says why bother and does not
      use them at all. The other extreme can't code "Hello, World!" without 5
      layers of inheritance and a dozen composite objects.

      So the real question is, what jobs are they good for? Also, what kind of
      site are you building? Is there something you are having trouble doing?

      In our system we write database applications, we use a dispatcher and
      functions, plus a scheme for storing lots of config parms in
      ready-to-execute include files that populate associative arrays. This
      takes care of 99% of cases.

      The only place where I have found it actually easier to use a class is for
      providing overrides to default behavior. The one single class we have
      contains some very basic behaviors, and contains calls at different points
      to empty class methods. If I need to override default behavior, I make up
      a class for that page (normally I don't need a class for most pages, the
      libraries know what to do), and code up one or two of those trigger methods
      to nudge processing in one direction or another.

      But as for making one-class-per-table, yuck.

      --
      Kenneth Downs
      Secure Data Software, Inc.
      (Ken)nneth@(Sec )ure(Dat)a(.com )

      Comment

      • Mike Willbanks

        #4
        Re: Advantages of using classes over functions?

        Burnsy,
        [color=blue]
        > Generally if I re-use code, I use a function. If I need to use these
        > functions over a number of pages I write the function to an include
        > file where all pages have access.
        >
        > So when should I ever use PHP classes instead. I have learned how to
        > put together PHP classes but never seen a reason to use them where I
        > can simply use a function.
        >
        > Im basically just wanting to know classes benefits over functions. If
        > something can be better put together in a class I would like to be
        > doing it that way. Any suggestions?[/color]


        Normally I code a massive amount of objects and simple functions and
        arrays of configuration.

        What I normally do is put all of my business logic into classes that
        have actions. Then as the last poster noted that you can always extend
        those operations which makes it extremely scalable.

        Most things that I use for objects are authentication and also database.
        This helps when I transfer to different DBs (have had to do it a
        couple times, not pretty when things are just coded to one specific item).


        Another nice thing about objects is it gives you a chance to group all
        of your functions and have variables that can be global to all the
        functions but not global within the scripts. That can help massively on
        many cases. (template systems are huge examples of this type of
        importance).

        I'm sure there will be more stuff posted later but as stated before it
        is a all about your opinion.

        Mike

        Comment

        • Chuck Anderson

          #5
          Re: Advantages of using classes over functions?

          bissatch@yahoo. co.uk wrote:
          [color=blue]
          >Hi,
          >
          >Generally if I re-use code, I use a function. If I need to use these
          >functions over a number of pages I write the function to an include
          >file where all pages have access.
          >
          >So when should I ever use PHP classes instead. I have learned how to
          >put together PHP classes but never seen a reason to use them where I
          >can simply use a function.
          >
          >Im basically just wanting to know classes benefits over functions. If
          >something can be better put together in a class I would like to be
          >doing it that way. Any suggestions?
          >
          >Cheers
          >
          >Burnsy
          >
          >
          >[/color]
          This brings up a question I have (hope it's okay to divert the topic
          slightly). Should I write a common piece of code as a callable function,
          or should I just make it some script that I can include (seems like it
          would save the function call). If I write a function, I have to include
          the file where I keep the function, anyway. So I tend to simply include
          the "function" inline and then document the include file with pseudo
          inputs and outputs (what vars does it depend on and what vars does it
          change).

          --
          *************** **************
          Chuck Anderson • Boulder, CO

          Integrity is obvious.
          The lack of it is common.
          *************** **************

          Comment

          • Jerry Stuckle

            #6
            Re: Advantages of using classes over functions?

            bissatch@yahoo. co.uk wrote:[color=blue]
            > Hi,
            >
            > Generally if I re-use code, I use a function. If I need to use these
            > functions over a number of pages I write the function to an include
            > file where all pages have access.
            >
            > So when should I ever use PHP classes instead. I have learned how to
            > put together PHP classes but never seen a reason to use them where I
            > can simply use a function.
            >
            > Im basically just wanting to know classes benefits over functions. If
            > something can be better put together in a class I would like to be
            > doing it that way. Any suggestions?
            >
            > Cheers
            >
            > Burnsy
            >[/color]


            As Jacob said, this all goes back to whether Object Oriented programming
            is "better" than structured programming.

            Basically - variables have states (hold information). Functions have
            behavior (do things). Objects (the instantiation of classes in PHP)
            have both.

            Classes have an additional feature, though. They can abstract the data.
            For instance - I create a lot of database classes. It doesn't take
            long, but it has advantages. For instance - due to a change in
            requirements on one site recently, I had to split a table. Basically, I
            had the original table minus a little data. That missing data went into
            a second table. A third table provided linkage between the other two.

            There were > 200 pages dependent at least in part on this table. How
            many needed to be changed? Zero. Everything was in a class; I modified
            the class to handle three tables instead of one. I had to change two
            administrative pages which were the actual cause of the change. But
            everything else was OK.

            Generally, writing OO code does take longer than non-OO code, just as
            writing functions takes longer than doing something inline. The
            advantage come when you reuse the code, or, as in above, need to make
            changes to the back end.

            OO is not the best in every circumstance. But it has its advantages.

            --
            =============== ===
            Remove the "x" from my email address
            Jerry Stuckle
            JDS Computer Training Corp.
            jstucklex@attgl obal.net
            =============== ===

            Comment

            • Mike Willbanks

              #7
              Re: Advantages of using classes over functions?

              > Generally, writing OO code does take longer than non-OO code, just as[color=blue]
              > writing functions takes longer than doing something inline. The
              > advantage come when you reuse the code, or, as in above, need to make
              > changes to the back end.[/color]

              Taking longer is a common misconception. It's the same thing with most
              programming. The more you do it the less time it takes.

              Also a class with structures I already have in place, I have a specific
              way I write my objects. When I first started writing objects and trying
              to find a way to make it as reusable as possible I was taking around 1
              hr to write the class now that time is down to around 15 minutes.

              Now when I look at that type of time I then look at how long it will
              take me for a page that does not use my objects I have already written
              and then just writing it all in one file and between using my reusable
              code and creating one big file is a change from around 2 hours to 30
              minutes.

              The reason is that my reusable code has been tested many times, the
              expected actions are tested and the limitations known. This way you do
              not recreate the wheel.

              But the same can be said for simple include files. I just like it
              because of the difference in namespaces and I can use any variables
              without cluttering the files and have to worry about using an existing
              variable.

              So I think that also needs to be looked at when using OOP. Is the
              namespace :)

              Mike

              Comment

              • Peter Fox

                #8
                Re: Advantages of using classes over functions?

                Following on from 's message. . .[color=blue]
                >So when should I ever use PHP classes instead. I have learned how to
                >put together PHP classes but never seen a reason to use them where I
                >can simply use a function.
                >
                >Im basically just wanting to know classes benefits over functions. If
                >something can be better put together in a class I would like to be
                >doing it that way. Any suggestions?[/color]
                * Classes are good for when data needs to be packaged. This makes it
                easier to use with sessions and do checks etc on it. So for example you
                might have a user class which contains name, ID to start with plus
                'embedded' functions for checking password etc. Stuff it in the session
                and Bobs your uncle. Now add access permissions - (some data and some
                manipulation functions) without having to touch the way the data gets
                passes around behind the scenes in PHP. This also means it is ready to
                run for your next project.

                * If you have lots of components that get stuck together and contain
                others then wrapping your data and operations up in classes means you
                can deal with 'black-boxes'.

                * Classes for classes sake are a pain.

                * The trouble with OO is that you need to think before you code. There
                is an art to this of course. IMHO you should look at the self-contained
                elements for objectivising and small-scale common activities for
                functionising.

                * Reference documentation is possible but you need tools to do it. I
                wrote my own.

                * Finally you can put a huge amount of complexity into a single object
                which is fantastic if you want to work with complex objects as building
                blocks. Pre-fabrication. For example this is a screen with in-line
                editing in a table, with standard layout features, navigation buttons,
                and all database twiddles wrapped up inside somewhere. (Actually this
                gets compiled into a database which a screen server picks out as
                required so there is a whole lot of overhead but it means that if you
                want a 100 screen system you can have it in no time flat.)

                $SCREENOBJECT = new stdScreen('suta ble','Suppliers ','','menu01');
                $SCREENOBJECT->AddBlock(new
                buttonBlock(HAR ,BUADD,'suedit? ID=0','Add','Ne w supplier'));

                $t=new tableElement('s elect SuID,SuName,SuT el,SuOurNote,Su Address from
                supplier order by SuName','No suppliers!');
                $t->AddCol('Name', '[SuName]');
                $t->AddCol('Tel' ,'[SuTel]');
                $t->AddButton('Det ails',BUGO,'sue dit?ID=[SuID]');
                $t->AddEditArea('A ddress','','add r[SuID]','[SuAddress]',20,2);
                $t->AddEditArea('N otes','','note[SuID]','[SuOurNote]',20,2);

                $sb = new stdBlock('');
                $sb->SetActiveEleme nt($t);
                $SCREENOBJECT->AddBlock($sb );


                --
                PETER FOX Not the same since the bottom fell out of the bucket business
                peterfox@eminen t.demon.co.uk.n ot.this.bit.no. html
                2 Tees Close, Witham, Essex.
                Gravity beer in Essex <http://www.eminent.dem on.co.uk>

                Comment

                • Peter Fox

                  #9
                  Re: Advantages of using classes over functions?

                  Following on from 's message. . .[color=blue]
                  >So when should I ever use PHP classes instead. I have learned how to
                  >put together PHP classes but never seen a reason to use them where I
                  >can simply use a function.
                  >
                  >Im basically just wanting to know classes benefits over functions. If
                  >something can be better put together in a class I would like to be
                  >doing it that way. Any suggestions?[/color]
                  * Classes are good for when data needs to be packaged. This makes it
                  easier to use with sessions and do checks etc on it. So for example you
                  might have a user class which contains name, ID to start with plus
                  'embedded' functions for checking password etc. Stuff it in the session
                  and Bobs your uncle. Now add access permissions - (some data and some
                  manipulation functions) without having to touch the way the data gets
                  passes around behind the scenes in PHP. This also means it is ready to
                  run for your next project.

                  * If you have lots of components that get stuck together and contain
                  others then wrapping your data and operations up in classes means you
                  can deal with 'black-boxes'.

                  * Classes for classes sake are a pain.

                  * The trouble with OO is that you need to think before you code. There
                  is an art to this of course. IMHO you should look at the self-contained
                  elements for objectivising and small-scale common activities for
                  functionising.

                  * Reference documentation is possible but you need tools to do it. I
                  wrote my own.

                  * Finally you can put a huge amount of complexity into a single object
                  which is fantastic if you want to work with complex objects as building
                  blocks. Pre-fabrication. For example this is a screen with in-line
                  editing in a table, with standard layout features, navigation buttons,
                  and all database twiddles wrapped up inside somewhere. (Actually this
                  gets compiled into a database which a screen server picks out as
                  required so there is a whole lot of overhead but it means that if you
                  want a 100 screen system you can have it in no time flat.)

                  $SCREENOBJECT = new stdScreen('suta ble','Suppliers ','','menu01');
                  $SCREENOBJECT->AddBlock(new
                  buttonBlock(HAR ,BUADD,'suedit? ID=0','Add','Ne w supplier'));

                  $t=new tableElement('s elect SuID,SuName,SuT el,SuOurNote,Su Address from
                  supplier order by SuName','No suppliers!');
                  $t->AddCol('Name', '[SuName]');
                  $t->AddCol('Tel' ,'[SuTel]');
                  $t->AddButton('Det ails',BUGO,'sue dit?ID=[SuID]');
                  $t->AddEditArea('A ddress','','add r[SuID]','[SuAddress]',20,2);
                  $t->AddEditArea('N otes','','note[SuID]','[SuOurNote]',20,2);

                  $sb = new stdBlock('');
                  $sb->SetActiveEleme nt($t);
                  $SCREENOBJECT->AddBlock($sb );


                  --
                  PETER FOX Not the same since the bottom fell out of the bucket business
                  peterfox@eminen t.demon.co.uk.n ot.this.bit.no. html
                  2 Tees Close, Witham, Essex.
                  Gravity beer in Essex <http://www.eminent.dem on.co.uk>

                  Comment

                  • juglesh

                    #10
                    Re: Advantages of using classes over functions?

                    So far (oh, maybe 9 months of php) I havent figured out the benefit
                    either. For one thing, I dont like great big files full of functions.
                    I usually break peices of code and functions out to a separate file,
                    then include() it. When i want to reuse code, i just include
                    thatFunction.ph p at the top of the main script, then call the function
                    at the appropriate place. So, my scrpits end up having a bunch of
                    include()s at the top. To me, it makes it easier to trouble shoot a
                    particular function. I keep folders full of ThisOrThatType of
                    function.

                    j

                    Comment

                    • juglesh

                      #11
                      Re: Advantages of using classes over functions?

                      So far (oh, maybe 9 months of php) I havent figured out the benefit
                      either. For one thing, I dont like great big files full of functions.
                      I usually break peices of code and functions out to a separate file,
                      then include() it. When i want to reuse code, i just include
                      thatFunction.ph p at the top of the main script, then call the function
                      at the appropriate place. So, my scrpits end up having a bunch of
                      include()s at the top. To me, it makes it easier to trouble shoot a
                      particular function. I keep folders full of ThisOrThatType of
                      function.

                      j

                      Comment

                      • lkrubner@geocities.com

                        #12
                        Re: Advantages of using classes over functions?


                        OOP may have some advantages for very large systems, but most of those
                        advantages belong to things that are not strictly OOP: strict variable
                        typing, type checking on all passed and returned variables, exception
                        handling.

                        My current code is nearly all OOP because OOP encourages certain
                        stylistic improvements that help me with error checking. But there is
                        nothing I do with OOP that you couldn't also do procedurally.

                        Comment

                        • Oli Filth

                          #13
                          Re: Advantages of using classes over functions?

                          lkrub...@geocit ies.com wrote:[color=blue]
                          > OOP may have some advantages for very large systems, but most of[/color]
                          those[color=blue]
                          > advantages belong to things that are not strictly OOP: strict[/color]
                          variable[color=blue]
                          > typing, type checking on all passed and returned variables, exception
                          > handling.[/color]

                          You're neglecting the incredibly powerful concepts of inheritance,
                          polymorphism, abstraction and encapsulation. OOP isn't just traditional
                          procedural code with slightly different syntax, it's a whole different
                          way of breaking down problems and representing structures.

                          OOP has nothing to do with type-checking and exception handling.
                          [color=blue]
                          > My current code is nearly all OOP because OOP encourages certain
                          > stylistic improvements that help me with error checking. But there is
                          > nothing I do with OOP that you couldn't also do procedurally.[/color]

                          Comment

                          Working...