PHP Class Constructor -- Alternative Return

lomn75

Purple Ace
Joined
Jun 26, 2000
Messages
6,613
One major question, one semi-related minor question:

I've got a class whose constructor takes some arguments and uses those to pull data from a database. However, it's entirely possible that the arguments won't find squat in the database. Can (and how can) I cause the constructor to just return FALSE rather than an object?

code summary of my rough guess
Code:
class foo {
  function foo ($arg)
  {
    $found = $this->populate($arg); // database lookup function, boolean return
    if (!$found) return FALSE;
  }
}

Sorta related question: I know the "foo() or die()" method of error handling, is there a way to do "foo() or return FALSE" ?
 
if you use a scaler data type, which basicly all that PHP uses, just setting it to false should do that. and when you make the function call, you could do it like
PHP:
if(!$something = foo())
{
   do this;
}
and that will catch when its false only. Also, if something comes back as 0, it is concidered false as well, so watch for that. Also, I MAY be wrong about the above, if so, some one please correct me.

as for the foo() or return FALSE, that basicly all you need to do. if the first succeceds, it won't check the next due to short circut, other wise it does the second, which in this case would be to return false. its very common from what I understand.
 
I should have mentioned, on the second one:
code in use
Code:
mysql_free_result($this->_result) or return FALSE;
error message
PHP 5.0.0 said:
Parse error: parse error, unexpected T_RETURN
context: building a basic MySQL wrapper class. I'd use PEAR::DB, but this is for distribution and I don't want to add that to the "you must have to run this" list.
 
Well, I did say I could be wrong. what you could do though is use and if statement then, like such

PHP:
if ( !mysql_free_result($this->_result) )
{
   return FALSE;
}

Also, I want to say PEAR::DB is included with most of the PHP packages now, or at least a small part of PEAR is. How far back version wise are you planing on making this class/package for?
 
i know in one method i set $this = new thisClass($newParm); and it works, can you do $this = false; return false; maybe? i was thinking about trying it but haven't gotten around to it.
 
> and that will catch when its false only.

Are you _really_ sure assignment is what you want there?
 
eloj said:
> and that will catch when its false only.

Are you _really_ sure assignment is what you want there?

That's why I've gotten into the habit of reversing my parameters.

I read it somewhere, can't recall where. So, now I write:

Code:
if (false == $testForTruth) { ...

That way, the compiler/interpreter/whatever will bark at me if I forget an equals sign, saying that I can't assign to a constant. Much simpler debugging. :)
 
Back
Top