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.

13 comments »