SitePoint Sponsor

User Tag List

View Poll Results: Do you use setters and getters to attributes of a class within that class?

Voters
123. You may not vote on this poll
  • yes

    58 47.15%
  • no

    38 30.89%
  • undecided

    12 9.76%
  • what are you talking about? xD

    15 12.20%
Page 1 of 4 1234 LastLast
Results 1 to 25 of 93
  1. #1
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Do you use setters and getters within a class as well?

    Just wondering whether you access the class's attributes within the class itself directly or via their getter methods, which are meant for the public.

    The advantage would be less code (saving some brackets) and one would probably have special methods anyway if one needs the attributes in a special format.

    How do you go about it?

  2. #2
    SitePoint Evangelist Scheisskopf's Avatar
    Join Date
    Nov 2004
    Location
    Southampton, UK
    Posts
    537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Get and Set methods are meant for external classes, not inside the class. You could argue that they're not really necessary at all, considering PHP doesn't even have private attributes...

  3. #3
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hrm, I think PHP5 has private attributes...

  4. #4
    SitePoint Evangelist Scheisskopf's Avatar
    Join Date
    Nov 2004
    Location
    Southampton, UK
    Posts
    537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeh but PHP5 is rubbish.

  5. #5
    SitePoint Guru OfficeOfTheLaw's Avatar
    Join Date
    Apr 2004
    Location
    Quincy
    Posts
    636
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Scheisskopf
    Get and Set methods are meant for external classes, not inside the class. You could argue that they're not really necessary at all, considering PHP doesn't even have private attributes...
    Not really. There's some instances you may need to do something special on get or set, or if you're using php5, you may even use type hinting to enforce a certain type.

    If I am setting a private method form somewhere inside a class (besides in the acutal get/set method) I normally always call the getter/setter method so that any logic I may apply inside those methods will be availble and keeps me from changing data in multiple places when changes occur.

    As for arguing that get/set are not needed at all, that's not an arguement, that's a newbish claim as directly accessing all the class properties no matter what smacks of blackbox violations.

    James Carr, Software Engineer


    assertEquals(newXPJob, you.ask(officeOfTheLaw));

  6. #6
    SitePoint Evangelist ghurtado's Avatar
    Join Date
    Sep 2003
    Location
    Wixom, Michigan
    Posts
    591
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would have like to have seen the poll be a little bit more specific as in "Do you use generic or specific accessors in your classes?", since some people (like myself), dont always use "setWhatever" when the number of attributes in a class is variable, and prefer the generic accesor flavor ("getVar('name') / setVar('name', $value)").

    Anyway, I answered it as "no", meaning "I don't use specific accessors all the time, but I do use generic accessors almost always". I guess I should have chosen "undecided"
    Garcia

  7. #7
    Employed Again Viflux's Avatar
    Join Date
    May 2003
    Location
    London, On.
    Posts
    1,130
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't understand the use of getVar('name') and it's counterpart setVar('name') within the class itself.

    The only reason I can see for wanting to use get/set internally is to provide a mechanism for manipulating the target of your get/set in some non-generic way. If you use getVar or setVar, you may as well just access the property directly.

    Or am I missing something here?

  8. #8
    SitePoint Evangelist Scheisskopf's Avatar
    Join Date
    Nov 2004
    Location
    Southampton, UK
    Posts
    537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The use of these methods is obvious in java, where you should general keep your variables private. I just don't see the point in PHP.

  9. #9
    Employed Again Viflux's Avatar
    Join Date
    May 2003
    Location
    London, On.
    Posts
    1,130
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Scheisskopf
    The use of these methods is obvious in java, where you should general keep your variables private. I just don't see the point in PHP.
    Why should you keep internal properties private in Java and not PHP?

  10. #10
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Depends.

    I use getter class methods where the Model interacts with the View for example. You do this because the Model parameters may change at a drop of the hat, which usually happens a lot.

    You change the property names within the Model class only, you do not need to alter the View which uses the Model in that case, as the getters remain as is. As for setter class methods, I don't bother, I set the class properties publically, which doesn't really matter in my view, as it happens in the lower layers anyway.

    As for not needing the use of setter and getter class methods is just pure fantasy. You do need them at some point, and you will find that you will use them. Frequently actually.

    Btw, PHP5 is not rubbish. It is one of the most modern, web scripting languages on the planet. If your not particularly happy developing with PHP then fine - go and find something else to develop with.

    But don't come here and start that rubbish. We've seen enough of it thank you.

  11. #11
    throw me a bone ... now bonefry's Avatar
    Join Date
    Nov 2004
    Location
    Romania
    Posts
    848
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Scheisskopf
    The use of these methods is obvious in java, where you should general keep your variables private. I just don't see the point in PHP.
    Why ? (dumb argument IMHO)

    Quote Originally Posted by Viflux
    The only reason I can see for wanting to use get/set internally is to provide a mechanism for manipulating the target of your get/set in some non-generic way. If you use getVar or setVar, you may as well just access the property directly.

    Or am I missing something here?
    PHP Code:
    class TimerTask {
        private 
    $timer;
        function 
    setTimer($value)
        {
            
    $value = (int)$value;
            if (
    time() >= $value)
                throw new 
    Exception("Time cannot be set in the past");
            
    $this->timer $value;
        }

    The point is to check properties on runtime or to return default values.

    Quote Originally Posted by Scheisskopf
    Get and Set methods are meant for external classes, not inside the class. You could argue that they're not really necessary at all, considering PHP doesn't even have private attributes...
    See above ...
    Also, I use them inside the class sometimes.
    And besides, are you forgetting children of a class ? Those cannot be called "external classes" as they have a looser access policy.

    Another reason would be the use of interfaces.
    If you want to use interfaces, you cannot specify direct properties inside interfaces, only methods.

  12. #12
    SitePoint Evangelist
    Join Date
    Aug 2005
    Posts
    453
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I came from a VB background where all object propertys are set via set and retrieved via get methods, I was astounded that php allowed such open access to class variables. In Php 5 you can have mock read only variables or mock set only variables by using set or get functions. If the variable is read only use the set function to return an error message when a user tries to set the property from code, and vice-versa for set only functions. The major use I can see is for data validation when setting class attributes, instead of having to check incoming data at multiple points in my ciode it can all be done in my set function within the class. Encapsulation is the whole point of OO programming, just like the construct and destruct functions the set and get are invaluable in OO design. As far as setting a variable from inside your code in the same class, you are the programmer and you have to make sure your data is valid for the target variable. Just as with the construct and destruct functions the zend engineers had a very good reason for making them part of the "magic functions".

  13. #13
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by ghurtado
    I would have like to have seen the poll be a little bit more specific as in "Do you use generic or specific accessors in your classes?", since some people (like myself), dont always use "setWhatever" when the number of attributes in a class is variable, and prefer the generic accesor flavor ("getVar('name') / setVar('name', $value)").

    Anyway, I answered it as "no", meaning "I don't use specific accessors all the time, but I do use generic accessors almost always". I guess I should have chosen "undecided"
    Well the poll is only about whether you use getters and setters (generic or not) within the exact same class they belong to. The question was not what type of getters or setters you use (generic or not). It is a yes/no question.

    Quote Originally Posted by Dr Livingston
    As for setter class methods, I don't bother, I set the class properties publically, which doesn't really matter in my view, as it happens in the lower layers anyway.
    Not good IMO, what if you wanted to add a specified tax to an amount of a class? You would need to do that in the client code...probably a thousand times instead of only once in a setter.

  14. #14
    Employed Again Viflux's Avatar
    Join Date
    May 2003
    Location
    London, On.
    Posts
    1,130
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by bonefry

    PHP Code:
    class TimerTask {
        private 
    $timer;
        function 
    setTimer($value)
        {
            
    $value = (int)$value;
            if (
    time() >= $value)
                throw new 
    Exception("Time cannot be set in the past");
            
    $this->timer $value;
        }

    The point is to check properties on runtime or to return default values.
    Ya, I understand that.

    But to use a generic get/set internally bypasses that.

    The poster to which my comments were directed suggested the following...


    PHP Code:
    class TimerTask {
        private 
    $timer;
        function 
    setValue$var $value )
        {
            
    $this->$var $value;
        }

    Which may, or may not, work. Regardless, it bypasses your ability to perform any checks on the variable.

  15. #15
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Which may, or may not, work. Regardless, it bypasses your ability to perform any checks on the variable.
    Why?

    PHP Code:
    class TimerTask {
        private 
    $timer;
        function 
    setValue$var $value )
        {
            if(
    $var == 'someAttribute) {
                  $value .= '
    blabla';
            }

            $this->$var = $value;
        }


  16. #16
    Employed Again Viflux's Avatar
    Join Date
    May 2003
    Location
    London, On.
    Posts
    1,130
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That seems like a longwinded bypass of using a setAttribute() for any variable you need/want to set.

    Suppose it comes down to opinion though.

  17. #17
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well IMO it's not only opinion, using generic setters you save a ton of code lines as you can simply copy the generic setters/getters into all classes where you need them allowing you to avoid writing a ton of setters/getters and that simply do the same job.

    One real drawback is that if you change the name of an attribute you would change all client code that uses it, which is really bad. With normal setters/getters you stay independent. However, normally your attribute names do not change often...one often just removes or adds attributes.

  18. #18
    throw me a bone ... now bonefry's Avatar
    Join Date
    Nov 2004
    Location
    Romania
    Posts
    848
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ruby rulez
    Code:
    class TimerTask
    	attr_reader :timer
    	
    	def timer=(value)
    		value = value.to_i if value != nil and !value.is_a?(Integer) and value.respond_to?(:to_i)
    		raise "Time must be a valid timestamp" if !value.is_a? Integer
    		raise "Cannot set time in the past" if value <= Time.now().to_i
    		@timer = value
    	end
    end

  19. #19
    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 DarkAngelBGE
    One real drawback is that if you change the name of an attribute you would change all client code that uses it, which is really bad. With normal setters/getters you stay independent. However, normally your attribute names do not change often...one often just removes or adds attributes.
    I suppose you could do that trick with a generic accessor aswell, although you may soon loose the overview if you do it too often.

  20. #20
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A large part of this question is about Containers in general. In this very long and inconclusive thread I came to the conclusion that the answer is different for PHP4, PHP5 and (hopefully PHP6). For PHP4, the $obj->set($key, $value) may be necessary and is certainly easier (and more PHPlike because it is "stringy"). In PHP5 you can almost pull off $obj->key = $value or $obj->setKey($value), but because the __set() and __call() functions are error handlers and not true property handlers you still have the problem with already defined properties. Hopefully PHP6 will add true property handlers.

    I would say that using a generic Container as the basis for many appropriate classes can open up some interesting possiblities for using objects in ways you hadn't thought of before.
    Christopher

  21. #21
    throw me a bone ... now bonefry's Avatar
    Join Date
    Nov 2004
    Location
    Romania
    Posts
    848
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arborint
    In PHP5 you can almost pull off $obj->key = $value or $obj->setKey($value), but because the __set() and __call() functions are error handlers and not true property handlers you still have the problem with already defined properties. Hopefully PHP6 will add true property handlers.
    Not really true. In fact the current setter/getter system in PHP5 is quite flexible and I like it.

    PHP Code:
        class TimeTask
        
    {    
            private 
    $_timer null;
                
            function 
    __set($property$value)
            {    
                try {
                    
    $method = new ReflectionMethod(get_class($this), 'set'.(strtoupper(substr($property,0,1)).substr($property,1)));            
                    
    $method->invoke($this$value);
                }
                catch (
    ReflectionException $e) {
                    throw new 
    Exception("$property setter is not defined");
                }
            }
            
            function 
    __get($property)
            {
                try {
                    
    $method = new ReflectionMethod(get_class($this), 'get'.(strtoupper(substr($property,0,1)).substr($property,1)));
                    return 
    $method->invoke($this);
                }
                catch (
    ReflectionException $e) {
                    throw new 
    Exception("$property getter is not defined");
                }
            }
            
            function 
    setTimer($value)
            {
                
    $value = (int)$value;
                if (
    $value <= time())
                    throw new 
    Exception("Cannot set time in the past");
                
    $this->_timer $value;
            }
            
            function 
    getMysqlDateTime()
            {
                return 
    date('Y-m-d H:i:s'$this->_timer);
            }
        }
        
        
    $t = new TimeTask();
        
        
    $t->timer time() + 10;
        
        echo 
    $t->mysqlDateTime;
        
        echo 
    $t->unknownProperty

  22. #22
    SitePoint Wizard
    Join Date
    May 2003
    Location
    Berlin, Germany
    Posts
    1,829
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Bonefry, not to be offensive or anything, but could you please comment on your code a bit - what makes it so flexible? Most of us don't have the time to read through all code listings, understand them and elaborate on them.

    Thank you in advance.

  23. #23
    throw me a bone ... now bonefry's Avatar
    Join Date
    Nov 2004
    Location
    Romania
    Posts
    848
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DarkAngelBGE
    Bonefry, not to be offensive or anything, but could you please comment on your code a bit - what makes it so flexible? Most of us don't have the time to read through all code listings, understand them and elaborate on them.

    Thank you in advance.
    Well, you should have the time. The code is easy enough to argument my point.

    And my point is that you can replace current properties because that was the point of __set and __get in the first place -> to define property handlers and not properties.

  24. #24
    SitePoint Enthusiast
    Join Date
    Jun 2004
    Location
    London
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getters and Setters are Evil, morally objectionable behavior.

    The get/set methods expose some of the implementation of the system, hiding implemenation leads for a good acid test of the quality of an OO system.
    Don't ask for the information that you need to do some work, instead ask the object that has the information to do the work for you.

    PHP Code:
    // Pseudocode example of getter/setter.
    Calculator ab;
    ...
    a.setValuea.getValue() + b.getValue()) 

    // Pseudocode example "Put" the system to work.
    Calculator ab;
    ...
    a.total
    Think about coarse v fine grained operations.
    Coarse-grained operation asks an object from a system to do a lot of work.
    A fine-grained operation asks for only a small of work.
    Generally coarse-grained operations/methods simplify the implemation code, eliminating the need for the get/set tER methods.
    Last edited by davro; Nov 1, 2005 at 16:21.
    David Stevens, create-inspire
    PHP London, www.phplondon.org

  25. #25
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by bonefry
    Not really true. In fact the current setter/getter system in PHP5 is quite flexible and I like it.
    My point was neither that the PHP5 system was not flexible, nor that you or I or anyone else doesn't like it. My point was that because __get()/__set() are error handlers (called only when the property does not exist) rather than accessor handlers they are not a complete accessor solution.
    Christopher


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
  •