SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Nov 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP Master, chapter 1 (OOP)

    Actually, I submitted this as an error, but maybe I better would have posted it here. At least nobody started off with calling me a monkey

    I have a problem with the Courier and Parcel classes on one of the first pages in chapter 1.
    In the constructor method of the Courier class it says: return true;
    Now I would expect to have a boolean returned instead of an object, but in practice that is not true. You can also return false or 'abacadabra', it does not matter, but it gives the wrong message to newbie OOPs.

    My second problem is the Parcel class. It has setCountry and setWeight methods, that return $this.
    Why? From my Java background, setters should reuturn void (or NULL in PHP terms) and getters whatever you want to get.
    Actually, I think, since there is a setter, there should also be a getter, and the properties weight and destinationcountry should be made protected.

    Last comment: the autoload function says: strtolower for the filenames, but in my code archive, the names of the files start with uppercase. On my Windows system I would not notice, but if I would upload this to my website, it would mysteriously go wrong.
    After this I stopped reading this chapter. I liked the security chapter though!

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,032
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    Regarding the constructor, you can't return anything there, since the constructor will always return the newly created object, regardless of what you say. This is indeed an error in the book.

    Regarding the return $this, that's used to create a so called "fluid interface" where you can "chain" methods. i.e.,

    PHP Code:
    <?php
    $parcel 
    = new Parcel();
    $parcel->setCountry('Netherlands')->setWeight(10);
    ?>
    as opposed to


    PHP Code:
    <?php
    $parcel 
    = new Parcel();
    $parcel->setCountry('Netherlands');
    $parcel->setWeight(10);
    ?>
    which is what you would do if the methods didn't return $this.

    This chaining is not used very much in PHP, but relied on heavily in javascript libraries like jQuery.

    Regarding the autoloading thing, sadly that is indeed completely wrong as well.
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    SitePoint Member
    Join Date
    Nov 2011
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm fine with your reply. Cheers.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •