SitePoint Sponsor

User Tag List

Page 1 of 3 123 LastLast
Results 1 to 25 of 59

Hybrid View

  1. #1
    SitePoint Addict chestertondevelopment's Avatar
    Join Date
    Dec 2005
    Location
    Essex, UK
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Advantages of Interfaces and Public Methods and Members

    I'm pretty new to the OO side of things and have a few questions to ask.

    1) What are the advantages of stating your members as public?
    i.e. Which is better?
    Code:
    class foo {
           var $bar;
           .....
        }
    or
    Code:
    class foo {
           public $bar;
           .....
        }
    At the moment I use var as it's shorter to write (I know i'm lazy). Are there any real reasons why public is better?

    2) Similar to the previous question, what are the advantages of stating your methods as public?
    At the moment I just leave any public methods without any declaration to their visibility. Is there anything wrong with this? Are there any advantages to stating their visibility?

    3) What are the advantages of using interfaces?
    As I said I'm fairly new to OOP and have looked a bit at interfaces. I don't see the point in them! Maybe I'm just not 'getting' interfaces but they seem very reduntant. If anyone has any good tutorials on Interfaces or reasons to use them I would appreciate it.

  2. #2
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    here's my take on it
    1. There's really no difference other than version compatibility. var is the PHP4 way, and public is the PHP5 way. So, if you're writing PHP5 and want PHP4 compatibility, use var. Note: In PHP5, if you don't explicitly state the visibility of a member, it's implicity public. All object members in PHP4 are public so this is irrelevant for PHP4.
    2. Same thing.
    3. Interfaces are like rules for developers. Functionally, I don't think there's any benefit. Since you can typehint in PHP5, and interfaces are treated like classes, you can write methods to expect a parameter object with certain interface without forcing the developer to extend one of your classes. Some of the SPL interfaces are good examples of this, such as Iterator.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  3. #3
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by stardustwd
    At the moment I use var as it's shorter to write (I know i'm lazy). Are there any real reasons why public is better?
    It's about E_STRICT compliance - which you'll hopefully be trying to attain. The keywords don't really differ in function, it's just that the other one is deprecated.
    At the moment I just leave any public methods without any declaration to their visibility. Is there anything wrong with this? Are there any advantages to stating their visibility?
    This one is a matter of preference. Others like to leave it out, I like to be explicit. Neither side is more wrong than the other.
    What are the advantages of using interfaces?
    This one is quite a different beast, compared to the previous questions. An interface is a signature; in conjunction with type hinting, you can use them to make sure that an object really provides the methods you are going to use. The advantage of interfaces over pure abstract classes is that you can have two classes that implement one without having common ancestors. You'll come to appreciate this as you venture further on the path of OOP.

    PHP5 also has the SPL library, which provides you with means to override certain functionalities such as iterating over an object, accessing it as an array etc. by implementing a predefined interface. It's quite powerful, and I recommend you take use of it when appropriate.

  4. #4
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    (1) & (2) None that I can think of. I'll be annoyed with the extra clutter whenever I finally move on from php4. It feels like a step back to Victorian times when people were mortified if a lady showed her ankles but nowadays we wonder what all the fuss was about. You can have a well-defined interface without them (nobody is doing $foo->bar, right...?) and I can't think of a unit test which would fail because something is public which should be private (private parts are not normally manipulated in unit tests).

  5. #5
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by McGruff
    You can have a well-defined interface without them (nobody is doing $foo->bar, right...?) and I can't think of a unit test which would fail because something is public which should be private (private parts are not normally manipulated in unit tests).
    Protected members makes it easier to refactor your code, because you can be sure that they are only used in a limited scope. Thus you will only have to check that code if you chahnge the member. I use protected whenever I can get away with it. I hardly ever use private though.
    For the sake of symmetry, I have begun writing out the redundant public, but I'm not sure it's really appropriate.

    Quote Originally Posted by stardustwd
    Thanks for the quick replies. I think I will start using global instead of var for my class members; didn't realise that var was deprecated.
    Uhm .. public ... not global

    Quote Originally Posted by stardustwd
    I can only really see the benefits of interfaces as you stated when using things such as iterators. It's only me using at the code so most of the time I feel that interfaces are reduntant. Has anyone got any good tutorials on interfaces so that I can understand them a little bit better?
    Interfaces are hard to understand - they are very powerful though. Design is equally important if you're a one man army as if you're working in a team.

    It's a bit academic, but I recently read this article, which among other things gives a good explanation of the role of interfaces vs. inheritance.

  6. #6
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In 5.2.0RC1, var is seemingly a psynonym for public and no longer raises a strict warning.
    Code:
    >php -r "error_reporting(E_ALL | E_STRICT); class P { var $p; } echo phpversion();"
    Just outputs..
    Code:
    5.2.0RC1

  7. #7
    SitePoint Addict chestertondevelopment's Avatar
    Join Date
    Dec 2005
    Location
    Essex, UK
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the quick replies. I think I will start using global instead of var for my class members; didn't realise that var was deprecated.

    As for methods, I'm still undecided. It seems as though it just creates a bit more clutter and is kind of unneccessary. Would like to hear other people's opinions on this though.

    Ezku, beetle: I can only really see the benefits of interfaces as you stated when using things such as iterators. It's only me using at the code so most of the time I feel that interfaces are reduntant. Has anyone got any good tutorials on interfaces so that I can understand them a little bit better?

    Thanks

  8. #8
    is_empty(2); foofoonet's Avatar
    Join Date
    Mar 2006
    Posts
    1,000
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by stardustwd
    Has anyone got any good tutorials on interfaces so that I can understand them a little bit better?
    Maybe there are tutorials out there, but the fact is its very easy to use an interface, but looks as though it isn't always obvious when you should do so.

    Below is not a tutorial, its a discussion but longer than this one is (so far) I really liked it and bookmarked it as the "barking dog interface" thread:

    http://www.sitepoint.com/forums/showthread.php?t=353663
    Upgrading to Mysql 5? Auto-increment fields now strict
    use NULL
    Or zero or leave the field name out completely.

  9. #9
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, regarding interfaces, consider the following.
    PHP Code:
     <?php
     
     
    class Config
     
    {
         public function 
    isDev()
         {
             
    // example
             
    return ( $_SERVER['DEV'] == );
         }
     }
     
     class 
    DomainObject
     
    {
         protected 
    $config;
         
         public function 
    __constructConfig $config )
         {
             
    $this->config $config;
         }
         
         public function 
    logError$message )
         {
             if ( 
    $this->config->isDev() )
             {
                 echo 
    'Error! <br/>';
                 echo 
    '<pre>';
                 
    print_r$message );
                 echo 
    '</pre>';
                 exit;
             } else {
                 
    mail'admin@site.com''Error'$message );
                 
    header"Location: /404.htm" );
                 exit;
             }
         }
     }
     
     
    ?>
    For DomainObject, we don't really care that $config is a Config object, or a subclass of it. But, with how we've setup our script, all we care about is that $config has the isDev() method. Here's another approach using an interface instead

    PHP Code:
     <?php
     
     
    interface iConfig
     
    {
         public function 
    isDev();
     }
     
     class 
    Config implements iConfig
     
    {
         public function 
    isDev()
         {
             
    // example
             
    return ( $_SERVER['DEV'] == );
         }
     }
     
     class 
    DomainObject
     
    {
         protected 
    $config;
         
         public function 
    __constructiConfig $config )
         {
             
    $this->config $config;
         }
         
         public function 
    logError$message )
         {
             if ( 
    $this->config->isDev() )
             {
                 echo 
    'Error! <br/>';
                 echo 
    '<pre>';
                 
    print_r$message );
                 echo 
    '</pre>';
                 exit;
             } else {
                 
    mail'admin@site.com''Error'$message );
                 
    header"Location: /404.htm" );
                 exit;
             }
         }
     }
     
     
    ?>
    Looks almost the same - but this time DomainObject::logError expects config to use the interface iConfig. This means ANY object can be passed in as long as it implements the interface, so we're no longer forcing the user (code) to extend the Config class. Try to pass in anything else, and PHP will trigger a fatal error.


    P.S. This is just an example :P
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  10. #10
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by beetle
    Looks almost the same - but this time DomainObject::logError expects config to use the interface iConfig. This means ANY object can be passed in as long as it implements the interface, so we're no longer forcing the user (code) to extend the Config class. Try to pass in anything else, and PHP will trigger a fatal error.
    Which, of course, doesn't make much sense in a dynamic language like PHP anyway.

    Let me rewrite the above paragraph for the situation where you don't use the interface:

    This means ANY object can be passed in, so we're no longer forcing the user (code) to extend the Config class. Try to call isDev() method, and PHP will trigger a fatal error.

    That's called duck typing, and is much more appropriate for a dynamic language. Interfaces have their value, as documentation.

  11. #11
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by BerislavLopac
    Which, of course, doesn't make much sense in a dynamic language like PHP anyway.
    Why not?

    I don't ask that to be frictional, I really mean it. I'd rather make sure the user (coder) passed in an object with the correct interface than likely have an error anywhere else past that. Or, god forbid, they incidentally pass in an object that shares a method name but does something completely different.

    If an object was coded to an interface, it's much more likely the developer designed it as you intended. Documentation, indeed, but that's not all their good for IMO.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  12. #12
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by beetle
    Why not?

    I don't ask that to be frictional, I really mean it. I'd rather make sure the user (coder) passed in an object with the correct interface than likely have an error anywhere else past that.
    Let me return the favor by asking: why? What advantages do you have with that?

    In programming, more freedom is always better than more restrictions. Of course, we have all met bad programmers, but in the long run it much more pays off to educate (or fire if all else fails) bad developers than restrict everyone.

  13. #13
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by BerislavLopac
    In programming, more freedom is always better than more restrictions.
    Of course it is. But, that statement for one, doesn't change anything I said, and two, doesn't mean restrictions are never desirable.

    For example, tak using the SPL Iterator interface. You can't go in and change the methods names of a class that implements it from Object::current() to say... Object::currentElement() and still use Object in a foreach() loop.

    For the point I'm arguing, interfaces are a guide to achieveing the desired result by the programmer. I want x-object to work in a foreach() loop, so I implement Iterator. If ProgrammerB wants an object to behave in a system designed by ProgrammerA, ProgrammerB will implement InterfaceX because that's how ProgrammerA set it up.

    Back to your counterpoint. Yes, freedom is programming is good. But when working with something as part of a system, restrictions can be necessary. Unless you think you should have so much freedom that you could change Object::current() to Object::someThingElse() and still get the desired result.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  14. #14
    SitePoint Addict chestertondevelopment's Avatar
    Join Date
    Dec 2005
    Location
    Essex, UK
    Posts
    241
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Uhm .. public ... not global
    Doh! Yes, public.

    Thanks beetle, i think i might be finally getting my head around this.

    I've been thinking and I think it might be best to get a book on this. Can anyone recommend any decent OO books for PHP; I know the basics but I get a little lost on things like interfaces, abstract classes and the more advanced bits of it.

  15. #15
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Php Architect Guide to Design Patterns is worth getting hold of. Lot of material on unit testing as well as design patterns.

  16. #16
    SitePoint Evangelist jplush76's Avatar
    Join Date
    Nov 2003
    Location
    Los Angeles, CA
    Posts
    460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    here's another reason I exclusivley use php5 ....

    I'm in charge of creating a "framework" of sorts that let other application developers plug into and use parts of our system. Being able to define protected and private variables allows me to have tighter code because I know some lazy app developer isn't going to try and use my members directly but actually have to use the public API call I provide them

    cuts down on alot of bugs.
    My-Bic - Easiest AJAX/PHP Framework Around
    Now Debug PHP scripts with Firebug!

  17. #17
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by jplush76
    Being able to define protected and private variables allows me to have tighter code
    Not to mention other features benefitting that same goal - like abstract classes, final methods, and interfaces.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  18. #18
    SitePoint Wizard REMIYA's Avatar
    Join Date
    May 2005
    Posts
    1,351
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Think of public and private as a way to create a blackbox from your classes.

    Not much needed, unless you share them with other people

  19. #19
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    > Interfaces have their value, as documentation.

    Interfaces have other uses, and more to the point (the point that you so elegantly forget) have their purposes, and value, regardless of the language.

    > If an object was coded to an interface, it's much more likely the developer designed
    > it as you intended.

    That is how I see it; If I've spent a number of hours over a period of time designing an Interface(s) then that is how I would want the script to be implemented, not only by myself, but other developers that I employ and use my code base.

    Beris., if you have such as issue with PHP5, then go back to PHP4 where you won't have to face the use of Interfaces

  20. #20
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    Beris., if you have such as issue with PHP5, then go back to PHP4 where you won't have to face the use of Interfaces
    OK, I've noticed the smiley, but I don't know how you dediced that I have an issue with PHP5. I certainly have issues with some bad practices in some "modern" languages, which were for some reason taken by PHP5.

    1. Static-typing (and interfaces as its spawn): In static languages like Java, interfaces are a way to make variables "dynamic", i.e. to be able to put completely unrelated objects (in the sense of inheritance) to a same variable; in dynamic languages that need doesn't exist. I mean, interfaces always exist, simply as a collection of an object's public members, and if an object doesn't comply with the interface you need it will show up as soon as you try using it.

    2. Confusion of classes and objects: as I mentioned in another thread, the whole private/protected/public (and package in Java) mess came up because of confusion between classes and objects. Visibility of a property should not affect its extendability, and especially the idea that a private (or any for that matter) property cannot be inherited is an utter nonsense. The OO principles call for a) all properties must be inherited, as they define a type, and b) properties should be either private, which means that only their own instance can access them, and public, which means that any other instance of any class can access them (of course, private should be the default and public should be explicitely announced).

  21. #21
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I suppose the reasoning is that it prevents action at a distance, since the program would fail early. I agree with you about dynamic languages vs. interfaces. I think a sort of weak interfaces would be much more useful.

  22. #22
    SitePoint Guru 33degrees's Avatar
    Join Date
    May 2005
    Posts
    707
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In a truly dynamic language, you can add, remove and rename methods at will, which renders Interfaces completely useless. In a truly dynamic language, it doesn't matter what type an object is, the only thing that matters is, does it contain a given method?

    Now, I wouldn't use the word "misleading" to describe them, but they are definitely unneccesary.

  23. #23
    SitePoint Enthusiast
    Join Date
    Feb 2006
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think interfaces and type hinting are tools just like many other features of the language.

    Personally I like writing code like:

    PHP Code:
    function array_something(array $array) { } 
    instead of:

    PHP Code:
    function array_something($array) { 
    if(
    is_array($array)) throw new Exception("first argument should be an array"); 

    The first example has also the advantage of being a little bit self-documenting (You don't have to write the type of the first parameter in doc-block).

  24. #24
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by zYne
    PHP Code:
    function array_something(array $array) { } 
    And thus preventing a programmer from passing an ArrayAccess ?

  25. #25
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    And thus preventing a programmer from passing an ArrayAccess ?
    Yes. ArrayAccess' behaviour is a subset of array. You can't subject it to the common array manipulation functions, for example. Can you pass an array if the type hint says ArrayAccess, though?


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
  •