1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Why use getters and setters in PHP?

Discussion in 'PHP' started by eritrea1, Oct 15, 2013.

  1. #1
    Can anyone clarify in laymans terms, the importance of using getters and setters in PHP? other than for the purpose, of getting and setting a data in php?

    As in this example:


    class foobar{
        private $foo;
    
        public function getfoo() {
            return $this->foo;
        }
        public function setfoo($foo) {
            $this->foo= $foo;
        }
       
    }
    Code (markup):
    I assume, the one time I would use it for, is to set a property to value, and just get that value, but it seems the subject of getters and setters in more than that, but I can't see it.
     
    Solved! View solution.
    eritrea1, Oct 15, 2013 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,494
    Likes Received:
    4,457
    Best Answers:
    123
    Trophy Points:
    665
    #2
    It's not a PHP thing, its and Object Oriented Programming "standard practice"

    By using get and set functions it allows the programmer, in the future, to add validation, checks etc to the process.

    Lets say you have setfoo (as per your example above) and foo is actually the id of a customer's mobile phone record. Time passes and a new version of the phone is released and we want to slowly catch those users on the old phone and upsell them. So we add a session alert to the setfoo function to check if the id refers to an old phone and on the next screen they load they get an invitation to upgrade their phone. The function would also need to check if the invitation has already be checked and a few other things so would most likely be put into a separate funtion that just gets called from setfoo();

    but there might also be simple things like validating that the value of foo is correct and that the user hasn't given an invalid text string.
     
    sarahk, Oct 15, 2013 IP
  3. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #3
    Another reason would be when the properties aren't public or you want to limit the user to only set and/or get.
     
    ThePHPMaster, Oct 15, 2013 IP
    eritrea1 and deathshadow like this.
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Setters also allow you to control the value that's being assigned. Let's say you have a file upload class, and it only supports certain file types. With a setter you can make sure that only supported types are given:

    
    public function setExtension($extension = 'jpg')
    {
        if (!in_array($extension, ['jpg', 'png', 'gif'], true))
        {
            throw new Exception('Unsupported type');
        }
    
        $this->extension = $extension;
    }
    
    PHP:
    Without the setter, any extension could be provided, and that could cause problems elsewhere in your code.

    EDIT: In this example, you would have to make sure that $this->extension is a protected property, so no one can assign a value to it without the setter.
     
    nico_swd, Oct 16, 2013 IP
    eritrea1 likes this.
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #5
    Aka restricting scope. Something important in an interpreted / scripting language. Really I'm not a fan of setters as they pretty much defeat the purpose; if you have a 'setter' it should NOT be something that the value is passed to, and instead should pull the value from a static set (like a database). Doing it that way means you can make 'read only' variables that are scope restricted.

    Restricting scope limits what script injections can do should they (god forbid) occur -- It's why you aren't supposed to over-use global scope and NEVER put anything security related in same -- see why Turdpress' idiotic "Let's put the sql host, UN and PW in DEFINE" is one of it's biggest security holes, since even a minor injection in the blasted themes or a plugin can have full access to EVERYTHING. It's like locking the doors with the windows open.
     
    deathshadow, Oct 16, 2013 IP
    eritrea1 likes this.
  6. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #6


    Yeah, I can see it clearly in your example, but my question is: Why specifically should getters/setters come in, two pairs of function?
    Why can't it just be a protected property inside a class, like this:

    class foo{
      protected  $bar =  '';
      protected  $tar =  '';
      //..
    }
    Code (markup):
    Then, whenever you need to assign something:

    $o = new foo();
    $setBar = $o->bar = 'barValue';
    $getBar = $setBar;
    // the same logic can be applied, when extending another class too. 
    
    Code (markup):
    ?? It is likely, that this may be the a retarded idea you've seen in a while, but I don't know, why we need explicitly, a function to get/set anything?
    I think I am missing something here.
     
    eritrea1, Oct 16, 2013 IP
  7. #7
    Try out the code you posted. It won't work, because you cannot assign protected properties from outside your class (unless you're extending said class). If you have properties that should not contain anything but a specific set of values, or an instance of a specific class, you'd preferably use a setter method.

    Let's take a caching class for example. You have one class that supports multiple caching engines (methods): Memcached and APC. In the setter, where the programmer can pick one of these engines, you make sure that he's not adding something your class can't work with.

    Therefore we create an interface, which is pretty much just a fancy way of specifying which methods a class should have. Then all caching engines implement that interface.
    
    // An interface that cache supported cache classes should implement
    interface CacheEngine
    {
        public function getValue($key);
        public function setValue($key, $value);
    }
    
    PHP:
    In your main caching class, in the setter, you type hint $engine, and make sure that the class implements said interface. By doing so, you know that $cacheEngine has a specific set of methods, which you can reliably call at any time.

    
    // Main caching class which supports multiple caching engines.
    class Cache
    {
        protected $cacheEngine = null;
    
        public function setCacheEngine(CacheEngine $engine)
        {
            $this->cacheEngine = $engine;
        }
    
        public function set($key, $value)
        {
            $this->cacheEngine->setValue($key, $value);
        }
    
        // ...
    }
    
    
    // Random caching classes
    class MemcachedEngine implements CacheEngine
    {
         // ...
    }
    
    class APCEngine implements CacheEngine
    {
        // ...
    }
    
    // Example class that doesn't implement CacheEngine
    class RandomClass
    {
        // ...
    }
    
    PHP:
    Now you do something like this:
    
    $cache = new Cache();
    $cache->setCacheEngine(new MemcachedEngine());
    // or...
    $cache->setCacheEngine(new APCEngine());
    // but...
    $cache->setCacheEngine(new RandomClass());
    // ... fails, because RandomClass doesn't implements the interface.
    
    PHP:
    ... this way you're always sure that $cacheEngine is what you expect it to be (an instance of a class that implements "CacheEngine"), and your class can handle it.

    Don't over-think this, though. Is most cases you don't need getters and setters. I only use them to prevent errors before they happen (and especially where they can happen).

    If you have a "User" class, and you want to change the user name, don't use a setter or getter. Just do:
    
    $user = new User();
    $user->name = 'Nico';
    
    PHP:
    In short, only use getters and setters where they make sense. Wildly adding them to support all properties doesn't make sense, and wastes CPU time.
     
    Last edited: Oct 16, 2013
    nico_swd, Oct 16, 2013 IP
    eritrea1 likes this.
  8. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #8
    Hmm, to bad you had to mention Interfaces as I am stranger to that concept ( I guess no surprises, considering I'm confused about getters/setters) Anyway, your example was very solid, and helpful, it may have given me so (unintended) understanding of interfaces along the way.

    Thanks. I'll surely read it once more, in the future.
     
    eritrea1, Oct 16, 2013 IP