Question

I am building some kind of a proxy pattern class for lazyloading SQL queries.

The proxy pattern uses __call, __get and __set for relaying calls on it's object, but sometimes there is no object, if the SQL did not return any rows.

My question is then, if i do a is_null() on the proxy class, is it possible to make the class return true then? I am thinking is there any SPL interface I can implement like Countable which makes the class work in count().

Any suggestions?

Was it helpful?

Solution

Sadly, this is not possible I'm afraid for a object passed to is_null to return true. Some alternative might be to:

  1. Use NullObjects, an interesting discussion on these can be found recently on sitepoint http://www.sitepoint.com/forums/showthread.php?t=630292

  2. Actually return null rather than an object, although this may not be possible in your situation.

OTHER TIPS

I don't know if this is of any help but by taking advantage of the __toString method you could possible achieve what you are looking for, but be warned, this is not at all clean code or best practice, the solution Rob suggested is actually better

You have to be using PHP5.2 or higher and take advantage of typecasting and the __toString magic method of PHP's class model

class Dummy 
{
    private $value;

    public function __construct($val)
    {
        $this->value = $val;
    }

    public function __toString()
    {
        return $this->value;
    }
}

$dummy = new Dummy('1');
if((string)$dummy) {
    echo "__toString evaluated as true".PHP_EOL;
} else {
    echo "__toString evaluated as false".PHP_EOL;
}

$dummy2 = new Dummy('0');
if((string)$dummy2) {
    echo "__toString evaluated as true".PHP_EOL;
} else {
    echo "__toString evaluated as false".PHP_EOL;
}

What happens here is the __toString method returns either the string 0 or string 1 (attention, don't return integers, return strings!)

'0' evaluates to false, '1' evaluates to true in if statement so it might be of help in your case too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top