Which is better OOP, and why?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dan

    Which is better OOP, and why?

    I have seen differing ways to pass values to a class:

    $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
    .....
    OR

    $db=new mysqlclass()
    $db->host='localhos t';
    $db->user='user';
    $db->passwd='passwd ';
    $db->database='data base';
    .....

    To me, the second looks like more typing. But if the argument list to the
    class changes, the latter would not be effected. I am trying to drag my
    brain (kicking and scratching) into OOP. Any thoughts on this would be
    appreciated.

    Thanks

    Dan


  • Justin Koivisto

    #2
    Re: Which is better OOP, and why?

    Dan wrote:
    [color=blue]
    > I have seen differing ways to pass values to a class:
    >
    > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
    > ....
    > OR
    >
    > $db=new mysqlclass()
    > $db->host='localhos t';
    > $db->user='user';
    > $db->passwd='passwd ';
    > $db->database='data base';[/color]

    Usually, I use both ways. For instance, in the class constructor, I
    allow parameters to be sent as arguements (usually in an array), but
    leave them optional.

    I set up mutator methods like:
    function setHost($x){ $this->host = $x; return TRUE; }
    function setUser($x){ $this->user = $x; return TRUE; }
    function setPass($x){ $this->passwd = $x; return TRUE; }
    function setDB($x){ $this->db = $x; return TRUE; }

    As well as accessor methods like:
    function getHost($x){ return $this->host; }
    function getUser($x){ return $this->user; }
    function getPass($x){ return $this->passwd; }
    function getDB($x){ return $this->db; }

    Then I have the ability to set up utility methods:
    function resetConnection (){ return $this->mysqlclass() ; }

    That way, if you want to change sql servers, you don't need to create
    another object, just use something like:

    $db->setHost='local host';
    $db->setUser='user' ;
    $db->setPass='passw d';
    $db->setDB='databas e';
    $db->resetConnectio n();

    You'd also be able to get the connection information via the accessor
    methods to check what conection you have open.

    This method also gives you the ability to change variable names in the
    class without effecting the API of it - making it easier to maintain and
    sometimes more portable.

    I guess it all depends if you want to go the true OOP route like C++
    where there are private and public methods, or like PHP4, where
    everything is public. I usually try to stick with the strict C++
    methodology in order to force myself to create better code. (My thinking
    here is that if I am forced to create all these methods, I may as well
    spend the extra few minutes checking all input and writing error codes
    and such that re easier to debug down the road.)

    --
    Justin Koivisto - spam@koivi.com
    PHP POSTERS: Please use comp.lang.php for PHP related questions,
    alt.php* groups are not recommended.
    Official Google SERPs SEO Competition: http://www.koivi.com/serps.php

    Comment

    • André Næss

      #3
      Re: Which is better OOP, and why?

      Dan:
      [color=blue]
      > I have seen differing ways to pass values to a class:
      >
      > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
      > ....
      > OR
      >
      > $db=new mysqlclass()
      > $db->host='localhos t';
      > $db->user='user';
      > $db->passwd='passwd ';
      > $db->database='data base';
      > ....
      >
      > To me, the second looks like more typing. But if the argument list to the
      > class changes, the latter would not be effected. I am trying to drag my
      > brain (kicking and scratching) into OOP. Any thoughts on this would be
      > appreciated.[/color]

      I'd like to add that the former makes it easier to avoid errors from
      forgetting to pass some necessary value, but I guess you can implement that
      kind of checks on your own.

      One thing I greatly miss in PHP is keyword arguments. This simple feature is
      very useful when generating HTML. For example you can have a syntax like:

      createTable(:bo rder 0, :cellpadding 1 , :cellspacing 1);

      But alas, this is not possible, and I haven't seen it suggested for the 5.0
      release.

      One possible option is to use a combination. Now I guess we can safely
      assume that the four parameters in your example are necessary. To add
      something similar to keyword arguments you can pass an associative array in
      addition containing these.

      Say we have the createTable function again, and let's assume that this
      function always expects a set of data to generate a table from. So we can
      have this signature:

      function createTable($da ta, $options);

      Where $options is expected to be an associative array of optional arguments
      which is obviously very simple to extend. It's not very elegant, but it
      works.

      IMO the worst solution is to use optional arguments. I've been in the same
      sort of problem myself where I had a list of optional arguments, and then I
      needed to change the value of the 4th. optional argument, yet let the 3
      first remain unchanged. In this case I had to look up and pass the default
      value of the 3 first parameters.

      I've also seen people use something like setOption('opti onName', 'value');
      but in most cases these feels like overkill. Finally you can of course use
      getters/setters for all the relevant options, again this feels like
      overkill most of the time.

      André Næss

      Comment

      • Phil Roberts

        #4
        Re: Which is better OOP, and why?

        With total disregard for any kind of safety measures André Næss
        <andrena.spamre allysucks@ifi.u io.no> leapt forth and uttered:
        [color=blue]
        > One possible option is to use a combination. Now I guess we can
        > safely assume that the four parameters in your example are
        > necessary. To add something similar to keyword arguments you can
        > pass an associative array in addition containing these.
        >[/color]

        Or you could pass the arguments as a string and roll your own
        argument parser.

        function argParse($str) {
        $arg_pairs = explode(',', $str);
        $arguments = array();
        foreach($arg_pa irs as $pair) {
        list($key, $val) = explode(' ', $pair);
        $arguments[trim($key)] = trim($val);
        }
        return $arguments;
        }

        Passing the hash array leads to less processing, but a lot more
        typing. I suppose it depends on your preference.

        --
        Phil Roberts | Nobody In Particular | http://www.flatnet.net/

        Comment

        • Tom Thackrey

          #5
          Re: Which is better OOP, and why?


          On 10-Feb-2004, "Dan" <jitdsm@aol.nos pam.please.com> wrote:
          [color=blue]
          > I have seen differing ways to pass values to a class:
          >
          > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
          > ....
          > OR
          >
          > $db=new mysqlclass()
          > $db->host='localhos t';
          > $db->user='user';
          > $db->passwd='passwd ';
          > $db->database='data base';
          > ....
          >
          > To me, the second looks like more typing. But if the argument list to the
          > class changes, the latter would not be effected. I am trying to drag my
          > brain (kicking and scratching) into OOP. Any thoughts on this would be
          > appreciated.[/color]

          Strict OOP would rule out the second approach because it violates
          encapsulation. You would have to create methods for setting/retrieving the
          values to/from the variables.

          $db->setHost('local host');

          --
          Tom Thackrey

          tom (at) creative (dash) light (dot) com
          do NOT send email to jamesbutler@wil lglen.net (it's reserved for spammers)

          Comment

          • ChronoFish

            #6
            Re: Which is better OOP, and why?


            "Justin Koivisto" <spam@koivi.com > wrote in message news:wf8Wb.203$ sS3.5236@news7. onvoy.net...[color=blue]
            > Dan wrote:
            >[color=green]
            > > I have seen differing ways to pass values to a class:
            > >
            > > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
            > > ....
            > > OR
            > >
            > > $db=new mysqlclass()[/color][/color]
            ....
            [color=blue]
            >
            > Usually, I use both ways. For instance, in the class constructor, I
            > allow parameters to be sent as arguements (usually in an array), but
            > leave them optional.
            >[/color]

            Yes I believe that this is best way to go. In OOP you want an object to be ready to go at creation time. If the programmer has to
            set a ton of variables manually, then it not only becomes a lot of typing, but the user of the class has to know too much. My rule
            of thumb is to have a constructor function that takes all the variable necessary to create the object. Optional variables may or may
            not be included in the constructor, but will have the ability to be set by accessor functions. Incidentally I don't typically allow
            accessor functions to set the core variables necessary to create the object.

            I think it's a bad habit to try to change an object's core once it's been instantiated. If the object has to morph that
            dramatically, then it probably (though not always) really represents a new object.

            -CF


            Comment

            • Justin Koivisto

              #7
              Re: Which is better OOP, and why?

              ChronoFish wrote:
              [color=blue]
              > "Justin Koivisto" <spam@koivi.com > wrote in message news:wf8Wb.203$ sS3.5236@news7. onvoy.net...
              >[color=green]
              >>Dan wrote:
              >>[color=darkred]
              >>>I have seen differing ways to pass values to a class:
              >>>
              >>>$db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
              >>>....
              >>>OR
              >>>
              >>>$db=new mysqlclass()[/color][/color]
              >[color=green]
              >>Usually, I use both ways. For instance, in the class constructor, I
              >>allow parameters to be sent as arguements (usually in an array), but
              >>leave them optional.[/color]
              >
              > Yes I believe that this is best way to go. In OOP you want an object to be ready to go at creation time. If the programmer has to
              > set a ton of variables manually, then it not only becomes a lot of typing, but the user of the class has to know too much. My rule
              > of thumb is to have a constructor function that takes all the variable necessary to create the object. Optional variables may or may
              > not be included in the constructor, but will have the ability to be set by accessor functions. Incidentally I don't typically allow
              > accessor functions to set the core variables necessary to create the object.
              >
              > I think it's a bad habit to try to change an object's core once it's been instantiated. If the object has to morph that
              > dramatically, then it probably (though not always) really represents a new object.[/color]

              That is usually true, so I don't use that type of stuff often (like the
              example of a method that called the constructor). However, I did create
              a class for online listings that did something like that. Once the
              object was created, you could use a load($id) method, then use mutators
              to change stuff followed by a save(). Since it was being used in a loop
              quite often, I created a clear() method that basically started over with
              an empty object. May not be the best solution, but it did cut down on
              processing (memory useage was almost identical) by about 2 seconds when
              dealing with several thousand listings.

              --
              Justin Koivisto - spam@koivi.com
              PHP POSTERS: Please use comp.lang.php for PHP related questions,
              alt.php* groups are not recommended.
              Official Google SERPs SEO Competition: http://www.koivi.com/serps.php

              Comment

              • Bruno Desthuilliers

                #8
                Re: Which is better OOP, and why?

                Justin Koivisto wrote:[color=blue]
                > Dan wrote:
                >[color=green]
                >> I have seen differing ways to pass values to a class:
                >>
                >> $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                >> ....
                >> OR
                >>
                >> $db=new mysqlclass()
                >> $db->host='localhos t';
                >> $db->user='user';
                >> $db->passwd='passwd ';
                >> $db->database='data base';[/color]
                >
                >
                > Usually, I use both ways. For instance, in the class constructor, I
                > allow parameters to be sent as arguements (usually in an array), but
                > leave them optional.[/color]

                So the object created without all necessary parameters is not usable.
                Bad Thing(tm).
                [color=blue]
                > I set up mutator methods like:
                > function setHost($x){ $this->host = $x; return TRUE; }
                > function setUser($x){ $this->user = $x; return TRUE; }
                > function setPass($x){ $this->passwd = $x; return TRUE; }
                > function setDB($x){ $this->db = $x; return TRUE; }[/color]
                [color=blue]
                > As well as accessor methods like:
                > function getHost($x){ return $this->host; }
                > function getUser($x){ return $this->user; }
                > function getPass($x){ return $this->passwd; }
                > function getDB($x){ return $this->db; }[/color]

                If your object expose all of it's internal state, it's bad luck. What
                happens if you instanciate the object with all parameters and then
                change the 'User' field only ?
                [color=blue]
                > Then I have the ability to set up utility methods:
                > function resetConnection (){ return $this->mysqlclass() ; }[/color]

                You don't need to expose all the object's internal state to write this
                kind of method :
                [color=blue]
                > That way, if you want to change sql servers, you don't need to create
                > another object, just use something like:
                >
                > $db->setHost='local host';
                > $db->setUser='user' ;
                > $db->setPass='passw d';
                > $db->setDB='databas e';
                > $db->resetConnectio n();[/color]

                lol, and yuck :(

                firstly, i'm afraid this code is awfully broken. Should be :
                $db->setHost('local host');

                Then, what happens with this :
                $db->setPass('');
                $db->resetConnectio n();

                For this to be not too awful, you'd need :
                $db->resetConnectio n('host', 'user', 'pass', 'db');

                But then - in this particular case - it's just like you've created a new
                object :
                $db = new Db('host', 'user', 'pass', 'db');

                [color=blue]
                > You'd also be able to get the connection information via the accessor
                > methods to check what conection you have open.[/color]

                And if you changed one of the connection information, and then did not
                'reset' connection ? out of sync info is worse than no info.
                [color=blue]
                > This method also gives you the ability to change variable names in the
                > class without effecting the API of it - making it easier to maintain and
                > sometimes more portable.[/color]

                Yes, what a great deal... internally rename '$this->user' to
                '$this->m_str_user_nam e' without affecting the 'API' (er...).
                [color=blue]
                > I guess it all depends if you want to go the true OOP route like C++
                > where there are private and public methods, or like PHP4, where
                > everything is public.[/color]

                What is 'public' is what you use outside of the class. What is 'private'
                is what you dont use outside of the class. No need to enforce this with
                builtin keywords and compiler checks.
                [color=blue]
                > I usually try to stick with the strict C++
                > methodology in order to force myself to create better code. (My thinking
                > here is that if I am forced to create all these methods, I may as well
                > spend the extra few minutes checking all input and writing error codes
                > and such that re easier to debug down the road.)[/color]

                Nothing forces you to write any getter/setter unless the client code
                really needs it. Should read the pragmatic programmer's advices :
                We improve the lives of professional developers. We create timely, practical books on classic and cutting-edge topics to help you learn and practice your craft, and accelerate your career. Come learn with us.


                Now i'm not telling that getter/setter are a Bad Thing by themselves,
                just that you should make a distinction between what is the class
                'Knowledge Responsability' (ie : what client code is entitled to ask the
                class) and what is in fact internal state. If you happen to query the
                object about it's internal state just in order to decide what you're
                going to tell him to do next, then you've broken encapsulation, and
                you'd better fix your code right now. One important rule here is that
                you never should bother about the internal state of an object before
                sending him a message.

                My 2 cents,
                Bruno

                Comment

                • Bruno Desthuilliers

                  #9
                  Re: Which is better OOP, and why?

                  Dan wrote:[color=blue]
                  > I have seen differing ways to pass values to a class:
                  >
                  > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                  > ....
                  > OR
                  >
                  > $db=new mysqlclass()
                  > $db->host='localhos t';
                  > $db->user='user';
                  > $db->passwd='passwd ';
                  > $db->database='data base';
                  > ....
                  >
                  > To me, the second looks like more typing. But if the argument list to the
                  > class changes, the latter would not be effected.[/color]

                  And what happens with this code ?

                  $db = new Db();
                  // no user, no pwd, no host, no nothing
                  $db->doSomething( );
                  // wham ! doSomething() supposed the object was fully initialized.
                  // Too bad


                  If the arg list of the ctor have to change, change it and change client
                  code. What's worse ? a clean fix, or a Q&D workaround ?

                  My 2 cents
                  Bruno

                  Comment

                  • Justin Koivisto

                    #10
                    Re: Which is better OOP, and why?

                    Bruno Desthuilliers wrote:
                    [color=blue]
                    > Justin Koivisto wrote:
                    >[color=green]
                    >> Dan wrote:
                    >>[color=darkred]
                    >>> I have seen differing ways to pass values to a class:
                    >>>
                    >>> $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                    >>> ....
                    >>> OR
                    >>>
                    >>> $db=new mysqlclass()
                    >>> $db->host='localhos t';
                    >>> $db->user='user';
                    >>> $db->passwd='passwd ';
                    >>> $db->database='data base';[/color]
                    >>
                    >> Usually, I use both ways. For instance, in the class constructor, I
                    >> allow parameters to be sent as arguements (usually in an array), but
                    >> leave them optional.[/color]
                    >
                    > So the object created without all necessary parameters is not usable.
                    > Bad Thing(tm).[/color]

                    I should have made that more clear. Objects that *need* stuff to work
                    would have them required, everything else is optional...

                    I do have a few classes that don't need to have anything passed to
                    work... It all depends on the implementation and what the class is for.
                    [color=blue][color=green]
                    >> I set up mutator methods like:
                    >> function setHost($x){ $this->host = $x; return TRUE; }
                    >> function setUser($x){ $this->user = $x; return TRUE; }
                    >> function setPass($x){ $this->passwd = $x; return TRUE; }
                    >> function setDB($x){ $this->db = $x; return TRUE; }[/color]
                    >[color=green]
                    >> As well as accessor methods like:
                    >> function getHost($x){ return $this->host; }
                    >> function getUser($x){ return $this->user; }
                    >> function getPass($x){ return $this->passwd; }
                    >> function getDB($x){ return $this->db; }[/color]
                    >
                    > If your object expose all of it's internal state, it's bad luck. What
                    > happens if you instanciate the object with all parameters and then
                    > change the 'User' field only ?[/color]

                    That was just as example... Again, it depends on what the class
                    represents and what it is used for.
                    [color=blue][color=green]
                    >> Then I have the ability to set up utility methods:
                    >> function resetConnection (){ return $this->mysqlclass() ; }[/color]
                    >
                    > You don't need to expose all the object's internal state to write this
                    > kind of method :
                    >[color=green]
                    >> That way, if you want to change sql servers, you don't need to create
                    >> another object, just use something like:
                    >>
                    >> $db->setHost='local host';
                    >> $db->setUser='user' ;
                    >> $db->setPass='passw d';
                    >> $db->setDB='databas e';
                    >> $db->resetConnectio n();[/color]
                    >
                    > lol, and yuck :([/color]

                    Funny, huh? Well, this works very well for an online listing class I
                    have. I use this method to set 3 or 4 options out of the 15 available to
                    the object at a time. I could set the variables directly, but then if I
                    want to add functions for checking in the class that's shot.
                    [color=blue]
                    > firstly, i'm afraid this code is awfully broken. Should be :
                    > $db->setHost('local host');[/color]

                    Ya, I was in a hurry and didn't look over the message...
                    [color=blue]
                    > Then, what happens with this :
                    > $db->setPass('');
                    > $db->resetConnectio n();[/color]

                    That's what internal class checking is for. In this instance, the
                    resetConnection might return FALSE and set an error code accessible by
                    $db->Error();
                    [color=blue]
                    > For this to be not too awful, you'd need :
                    > $db->resetConnectio n('host', 'user', 'pass', 'db');[/color]

                    No, maybe I only want to change the host, nothing else...
                    [color=blue]
                    > But then - in this particular case - it's just like you've created a new
                    > object :
                    > $db = new Db('host', 'user', 'pass', 'db');[/color]

                    Ya, this was just an illustrative example... I said that in another post.
                    [color=blue][color=green]
                    >> You'd also be able to get the connection information via the accessor
                    >> methods to check what conection you have open.[/color]
                    >
                    > And if you changed one of the connection information, and then did not
                    > 'reset' connection ? out of sync info is worse than no info.[/color]

                    Again, that's where class error handling comes in... has nobody ever
                    though of that stuff before!?
                    [color=blue][color=green]
                    >> This method also gives you the ability to change variable names in the
                    >> class without effecting the API of it - making it easier to maintain
                    >> and sometimes more portable.[/color]
                    >
                    > Yes, what a great deal... internally rename '$this->user' to
                    > '$this->m_str_user_nam e' without affecting the 'API' (er...).[/color]

                    Sure, you can just go about assining your variables to user-input
                    without checking... A more typical mutator would be like this (for example):

                    function setVariable($x) {
                    if($result=$thi s->_validate_type ($x)){
                    return TRUE;
                    }else{
                    $this->_ERROR=$result *-1;
                    return FALSE:
                    }
                    }
                    [color=blue][color=green]
                    >> I guess it all depends if you want to go the true OOP route like C++
                    >> where there are private and public methods, or like PHP4, where
                    >> everything is public.[/color]
                    >
                    > What is 'public' is what you use outside of the class. What is 'private'
                    > is what you dont use outside of the class. No need to enforce this with
                    > builtin keywords and compiler checks.[/color]

                    The author may know the difference, but if you give it to another
                    developer, how the hell would they know what they should and shouldn't
                    use - afterall, the average PHP coder doesn't provide enough
                    documentation to explain these types of things.
                    [color=blue][color=green]
                    >> I usually try to stick with the strict C++ methodology in order to
                    >> force myself to create better code. (My thinking here is that if I am
                    >> forced to create all these methods, I may as well spend the extra few
                    >> minutes checking all input and writing error codes and such that re
                    >> easier to debug down the road.)[/color]
                    >
                    > Nothing forces you to write any getter/setter unless the client code
                    > really needs it. Should read the pragmatic programmer's advices :
                    > http://www.pragmaticprogrammer.com/p...s/1998_05.html[/color]

                    Read something very similar to it before...
                    [color=blue]
                    > Now i'm not telling that getter/setter are a Bad Thing by themselves,
                    > just that you should make a distinction between what is the class
                    > 'Knowledge Responsability' (ie : what client code is entitled to ask the
                    > class) and what is in fact internal state. If you happen to query the
                    > object about it's internal state just in order to decide what you're
                    > going to tell him to do next, then you've broken encapsulation, and
                    > you'd better fix your code right now. One important rule here is that
                    > you never should bother about the internal state of an object before
                    > sending him a message.[/color]

                    <sic>Next time I won't bother with illustrative examples, I'll just talk
                    in ways that will confuse the poor OP more and eventually have them give
                    up on OOP so the rest of us can keep our share...</sic>

                    Don't read into examples like this just to prove you have a superior
                    intellect - it turns ppl off.

                    --
                    Justin Koivisto - spam@koivi.com
                    PHP POSTERS: Please use comp.lang.php for PHP related questions,
                    alt.php* groups are not recommended.
                    Official Google SERPs SEO Competition: http://www.koivi.com/serps.php

                    Comment

                    • Chung Leong

                      #11
                      Re: Which is better OOP, and why?

                      Pass an associative array to the constructor.

                      class mysqlclass {
                      function mysqlclass($par ams) {
                      foreach($params as $name => $value) {
                      $this->$name = $value;
                      }
                      }
                      }

                      mysqlclass(arra y(
                      "host" => "localhost" ,
                      "user" => "baby",
                      "password" => "the_dingo_ate_ my_baby",
                      "database" => "dingo"
                      ));



                      Uzytkownik "Dan" <jitdsm@aol.nos pam.please.com> napisal w wiadomosci
                      news:9R7Wb.1409 66$U%5.645984@a ttbi_s03...[color=blue]
                      > I have seen differing ways to pass values to a class:
                      >
                      > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                      > ....
                      > OR
                      >
                      > $db=new mysqlclass()
                      > $db->host='localhos t';
                      > $db->user='user';
                      > $db->passwd='passwd ';
                      > $db->database='data base';
                      > ....
                      >
                      > To me, the second looks like more typing. But if the argument list to the
                      > class changes, the latter would not be effected. I am trying to drag my
                      > brain (kicking and scratching) into OOP. Any thoughts on this would be
                      > appreciated.
                      >
                      > Thanks
                      >
                      > Dan
                      >
                      >[/color]


                      Comment

                      • R. Rajesh Jeba Anbiah

                        #12
                        Re: Which is better OOP, and why?

                        Justin Koivisto <spam@koivi.com > wrote in message news:<wf8Wb.203 $sS3.5236@news7 .onvoy.net>...[color=blue]
                        > Dan wrote:
                        >[color=green]
                        > > I have seen differing ways to pass values to a class:
                        > >
                        > > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                        > > ....
                        > > OR
                        > >
                        > > $db=new mysqlclass()
                        > > $db->host='localhos t';
                        > > $db->user='user';
                        > > $db->passwd='passwd ';
                        > > $db->database='data base';[/color]
                        >
                        > Usually, I use both ways. For instance, in the class constructor, I
                        > allow parameters to be sent as arguements (usually in an array), but
                        > leave them optional.
                        >
                        > I set up mutator methods like:
                        > function setHost($x){ $this->host = $x; return TRUE; }
                        > function setUser($x){ $this->user = $x; return TRUE; }
                        > function setPass($x){ $this->passwd = $x; return TRUE; }
                        > function setDB($x){ $this->db = $x; return TRUE; }
                        >
                        > As well as accessor methods like:
                        > function getHost($x){ return $this->host; }
                        > function getUser($x){ return $this->user; }
                        > function getPass($x){ return $this->passwd; }
                        > function getDB($x){ return $this->db; }[/color]

                        I have seen few of your classes before. I'm a good fan of your
                        style. And I prefer getter/setter that make the class highly reusable.
                        When we need to send so many variables (as in the case of PayPal or
                        Authorize.net), I would use

                        function setParameter($k ey, $value)
                        {
                        $this->params[$key] = $value;
                        }

                        I have grabbed the above logic from
                        <http://www.zend.com/codex.php?id=11 94&single=1> And now, I use Matt
                        Babineau's style; I like the underscore functions style to show it is
                        just internal function.

                        --
                        "Success = 10% sweat + 90% tears"
                        If you live in USA, please support John Edwards.
                        Email: rrjanbiah-at-Y!com

                        Comment

                        • Nikolai Chuvakhin

                          #13
                          Re: Which is better OOP, and why?

                          "Dan" <jitdsm@aol.nos pam.please.com> wrote in message
                          news:<9R7Wb.140 966$U%5.645984@ attbi_s03>...[color=blue]
                          >
                          > I have seen differing ways to pass values to a class:
                          >
                          > $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                          > ....
                          > OR
                          >
                          > $db=new mysqlclass()
                          > $db->host='localhos t';
                          > $db->user='user';
                          > $db->passwd='passwd ';
                          > $db->database='data base';
                          > ....[/color]

                          There's also third way:

                          $db = new mysqlclass()
                          $db->sethost('local host');
                          $db->setuser('user' );
                          $db->setpasswd('pas swd');
                          $db->setdatabase('d atabase');
                          [color=blue]
                          > To me, the second looks like more typing. But if the argument
                          > list to the class changes, the latter would not be effected.
                          > I am trying to drag my brain (kicking and scratching) into OOP.
                          > Any thoughts on this would be appreciated.[/color]

                          First and foremost, consider not doing any OOP at all. Abstraction
                          layers in PHP can be a taxing proposition...

                          Cheers,
                          NC

                          Comment

                          • Bruno Desthuilliers

                            #14
                            Re: Which is better OOP, and why?

                            Justin Koivisto wrote:[color=blue]
                            > Bruno Desthuilliers wrote:
                            >[color=green]
                            >> Justin Koivisto wrote:
                            >>[color=darkred]
                            >>> Dan wrote:
                            >>>
                            >>>> I have seen differing ways to pass values to a class:
                            >>>>
                            >>>> $db=new mysqlclass('loc alhost','user', 'passwd','datab ase');
                            >>>> ....
                            >>>> OR
                            >>>>
                            >>>> $db=new mysqlclass()
                            >>>> $db->host='localhos t';
                            >>>> $db->user='user';
                            >>>> $db->passwd='passwd ';
                            >>>> $db->database='data base';
                            >>>
                            >>>
                            >>> Usually, I use both ways. For instance, in the class constructor, I
                            >>> allow parameters to be sent as arguements (usually in an array), but
                            >>> leave them optional.[/color]
                            >>
                            >>
                            >> So the object created without all necessary parameters is not usable.
                            >> Bad Thing(tm).[/color]
                            >
                            >
                            > I should have made that more clear. Objects that *need* stuff to work
                            > would have them required, everything else is optional...[/color]

                            Ok, this is somewhat different from what I understood...
                            [color=blue]
                            > I do have a few classes that don't need to have anything passed to
                            > work... It all depends on the implementation and what the class is for.[/color]

                            Of course !-)
                            [color=blue][color=green][color=darkred]
                            >>> I set up mutator methods like:[/color][/color][/color]
                            (snip getters/setters)
                            [color=blue][color=green]
                            >> If your object expose all of it's internal state, it's bad luck. What
                            >> happens if you instanciate the object with all parameters and then
                            >> change the 'User' field only ?[/color]
                            >
                            > That was just as example... Again, it depends on what the class
                            > represents and what it is used for.[/color]

                            Ok, but in this case it might have been a bad exemple. Not that this is
                            'absolutely bad code' - one can't say without knowing the code and
                            context -, but because it's a bit misleading IMHO. Reading this, the OP
                            could believe that one needs to have getters/setters for all private
                            data members of a class.
                            [color=blue][color=green][color=darkred]
                            >>> Then I have the ability to set up utility methods:
                            >>> function resetConnection (){ return $this->mysqlclass() ; }[/color]
                            >>
                            >> You don't need to expose all the object's internal state to write this
                            >> kind of method :
                            >>[color=darkred]
                            >>> That way, if you want to change sql servers, you don't need to create
                            >>> another object, just use something like:
                            >>>
                            >>> $db->setHost='local host';
                            >>> $db->setUser='user' ;
                            >>> $db->setPass='passw d';
                            >>> $db->setDB='databas e';
                            >>> $db->resetConnectio n();[/color]
                            >>
                            >>
                            >> lol, and yuck :([/color]
                            >
                            > Funny, huh? Well, this works very well for an online listing class I
                            > have.[/color]

                            Non-OO code can work pretty-well, and be as good and efficient as OO
                            code !-)
                            [color=blue]
                            > I use this method to set 3 or 4 options out of the 15 available to
                            > the object at a time. I could set the variables directly, but then if I
                            > want to add functions for checking in the class that's shot.[/color]
                            [color=blue][color=green]
                            >> firstly, i'm afraid this code is awfully broken. Should be :
                            >> $db->setHost('local host');[/color]
                            >
                            > Ya, I was in a hurry and didn't look over the message...[/color]

                            This happens to me too !-)
                            [color=blue][color=green]
                            >> Then, what happens with this :
                            >> $db->setPass('');
                            >> $db->resetConnectio n();[/color]
                            >
                            > That's what internal class checking is for. In this instance, the
                            > resetConnection might return FALSE and set an error code accessible by
                            > $db->Error();[/color]

                            And you didn't check the return of $db->resetConnectio n(), did you ?-)
                            [color=blue][color=green]
                            >> For this to be not too awful, you'd need :
                            >> $db->resetConnectio n('host', 'user', 'pass', 'db');[/color]
                            >
                            > No, maybe I only want to change the host, nothing else...[/color]

                            Can do this with 'default' values.

                            class Db {
                            function resetConnection ($host, $user, $pwd, $db) {
                            if ($host != null) {
                            /* proceed with $host */
                            }
                            if ($user != null) {
                            /* proceed with user */
                            }
                            /* etc ... */
                            /* and now try and reset the connection */
                            }
                            }

                            Now you have an atomic operation, so
                            - you do not depend on any previous method calls
                            - the object's internal state is always 'in sync' with the current
                            connection

                            Then I do agree that keyword args would be just fine !-)

                            (snip)[color=blue][color=green][color=darkred]
                            >>> You'd also be able to get the connection information via the accessor
                            >>> methods to check what conection you have open.[/color]
                            >>
                            >> And if you changed one of the connection information, and then did not
                            >> 'reset' connection ? out of sync info is worse than no info.[/color]
                            >
                            > Again, that's where class error handling comes in... has nobody ever
                            > though of that stuff before!?[/color]

                            Why having complex error handling code when a pretty simple API can make
                            sure such errors won't happen first ?-)

                            Now with your example, just how would your error handling prevent the
                            problem ? Given the code you show, when the client code changes some
                            connection info via a setter and don't call resetConnection (),
                            connections infos are out of sync wrt the current connection.
                            [color=blue][color=green][color=darkred]
                            >>> This method also gives you the ability to change variable names in
                            >>> the class without effecting the API of it - making it easier to
                            >>> maintain and sometimes more portable.[/color]
                            >>
                            >> Yes, what a great deal... internally rename '$this->user' to
                            >> '$this->m_str_user_nam e' without affecting the 'API' (er...).[/color][/color]
                            [color=blue]
                            > Sure, you can just go about assining your variables to user-input
                            > without checking... A more typical mutator would be like this (for
                            > example):
                            >
                            > function setVariable($x) {
                            > if($result=$thi s->_validate_type ($x)){
                            > return TRUE;
                            > }else{
                            > $this->_ERROR=$result *-1;
                            > return FALSE:
                            > }
                            > }[/color]

                            Well, one of the good things to come with PHP5 are exceptions !-)

                            Now what I wanted to say is that encapsulation is more than just
                            wrapping data members access into getters/setters. It's about not
                            exposing anything that dont need to be exposed.
                            [color=blue][color=green][color=darkred]
                            >>> I guess it all depends if you want to go the true OOP route like C++
                            >>> where there are private and public methods, or like PHP4, where
                            >>> everything is public.[/color]
                            >>
                            >> What is 'public' is what you use outside of the class. What is
                            >> 'private' is what you dont use outside of the class. No need to
                            >> enforce this with builtin keywords and compiler checks.[/color]
                            >
                            > The author may know the difference, but if you give it to another
                            > developer, how the hell would they know what they should and shouldn't
                            > use[/color]

                            Some languages seems to go well with just some simple conventions. Like
                            prefixing protected members with '_' and private members with '__'.
                            [color=blue]
                            > - afterall, the average PHP coder doesn't provide enough
                            > documentation to explain these types of things.[/color]

                            Bad coder, Burn coder !-)

                            (snip)

                            <OT>[color=blue]
                            > <sic>Next time I won't bother with illustrative examples, I'll just talk
                            > in ways that will confuse the poor OP more[/color]

                            Please do bother with illustrative examples. It just happens that I
                            found your example actually confusing in some points, and explained why.
                            This as nothing to do with *you*, so why do you take it that way ? Did I
                            sound a bit harsh ? Sorry, but English is not my first language, so I
                            may sometime say things the simplest way. (Feel free to offer me some
                            English courses so I can express myself in a more subtle manner...)
                            [color=blue]
                            > and eventually have them give
                            > up on OOP so the rest of us can keep our share...</sic>
                            >
                            > Don't read into examples like this just to prove you have a superior
                            > intellect - it turns ppl off.[/color]

                            What's you problem, exactly ? Believe it or not, I'm not trying to prove
                            anything, nor did I attack you, so please let's keep this for what it is
                            : POW on OO, not a pissing contest. If you want to talk about PHP
                            programming and/or OO, that's fine with me. Now if you don't stand
                            criticism, well, too bad, but that's your problem, not mine.
                            </OT>

                            Comment

                            • Dan

                              #15
                              Re: Which is better OOP, and why?

                              Thanks to all those who replied (and those who replied to the replies).

                              After 20+ years of various flavors of BASIC, starting with a Sinclair 1000
                              (I think that was what it was called -- it had 2K RAM! I think I got it
                              sometime in 1981), I am really enjoying getting to know PHP. I have already
                              converted a few relatively complex applications from VBScript. These are
                              all procedural, line-by-line and translations of vb to php. I have many php
                              books - each with at least one chapter of OOP. I really found it difficult
                              to understand the advantages, as opposed to simply including files with the
                              functions I need. I finally just started to DO it, rather than just THINK
                              about it. These posts were worth more than many chapters in any php book.

                              Thanks again

                              Dan




                              Comment

                              Working...