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 o开发者_如何学编程bject, 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?
Sadly, this is not possible I'm afraid for a object passed to is_null to return true. Some alternative might be to:
Use NullObjects, an interesting discussion on these can be found recently on sitepoint http://www.sitepoint.com/forums/showthread.php?t=630292
Actually return null rather than an object, although this may not be possible in your situation.
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.
精彩评论