Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Dec 2005
    Posts
    217
    Thanks
    1
    Thanked 0 Times in 0 Posts

    which one to use and why ??

    Hello forums!!
    I am curious about some question which i am going to mention here.
    we know the advantage of using getters and setters in OOP.
    Let us consider the case:
    PHP Code:
    <?php
    class className{
        var 
    prop1;
        var 
    prop2;
        var 
    prop3;
        
        function 
    className(){
            
    // Empty constructor
        
    }
        
        function 
    setProp1($prop1){
            
    $this->prop1 $prop1;
        }
        function 
    getProp1(){
            return 
    $this->prop1;
        }
        function 
    setProp2($prop2){
            
    $this->prop2 $prop2;
        }
        function 
    getProp2(){
            return 
    $this->prop2;
        }    
        function 
    addProp12(){
            
    $value $this->prop1 $this->prop2;
            
    // Alt $value = $this->getProp1() + $this->getProp2();
            
    return $value;
        }
    }

    // Using Class
    $classObj = new className();
    $classObj->setProp1("x");
    $classObj->setProp2("y");
    echo 
    $classObj->addprop12();
    ?>
    My Question is very simple..
    once the property is set using methods, for internal use in the class file
    which one to use and why ?
    1> $value = $this->prop1 + $this->prop2;
    2> $value = $this->getProp1() + $this->getProp2();

    Thanks in advance to all of you.

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    I always use setter methods instead of public data in case I need to add validation to enforce restrictions on what values a given datum can have.

    Even if at the outset I don't care what $foo is, if I find out later something catastrophic happens when it is 0 I can add the validation to the setter without changing any client code. If I'm using public data I have to track down all the places I set that field (if that's even possible) and make sure I'm following the new protocol in each instance, or at least add a redundant check to ever method in my class that uses that datum. That could be an ugly maintenance scenario.

    That said I think using 'var' is the same as saying 'public' so it doesn't really matter: if you use var your interface is not mandatory. Use public/private/protected instead as appropriate.


  •  

    Posting Permissions

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