Quick Tip: Get, Set and Query in One Method

Posted by Stuart Herbert @ 9:06 AM, Mon 10 Dec 07

Filed under: 2 - Intermediate

13 Comments

I’m still working on the next article in my series looking at PHP on servers, so in the mean time, check out this simple way to emulate Ruby’s nice way of handling separate getter, setter and state query methods in PHP:

class Example {         private $canCache = false;         private $cacheXml = null;         function canCache($newState = null)         {                 // check if we are querying or changing state                 if ($newState === null)                {                       // we are querying                       return $this->canCache;                }               // if we get here, we are a traditional getter/setter method                if ($newState)                {                       $this->canCache = true;                       $this->cacheXml = $this->_toXml();                       return true;                }                else                {                       $this->canCache = false;                       unset($this->cacheXml);                       return false;                }         } } $exObj = new Example(); $exObj->canCache(true); if ($exObj->canCache()) {         // ... do something here }

It isn’t as elegant as Ruby, but it does the job, and it means that your classes don’t have to be full of seperate canDoSomething() and isSomethingAllowed() type methods. I think it makes the code that uses the object a little easier to read, and a little more intuitive. YMMV.

Did you enjoy this article? If so, subscribe to my RSS feed.

13 comments »

Categories

Archives

What's Stu Doing Now?

Latest Photos

N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot
N82 Test Shot

This Month

December 2007
S M T W T F S
« Nov   Jan »
 1
2345678
9101112131415
16171819202122
23242526272829
3031