On Wed, 6 Aug 2003 11:33:54 -0500, you wrote:

>Basically in the class I have methods that perform a task, and return true
>on success, or false on failure. Easy enough. If it returns false however, I
>want to display errors for the user. The best way I can think of doing this
>is adding a member variable to the class (an array). With each error
>encountered it would push them on the array and at the end of the function
>return false. Then in the code I would check if it returned false, and if so
>dive into the error member variable array of the class and display them...

That's pretty much the approach I use. It allows me to produce something
like a stack trace...

"Error: Can't connect to database in _runQuery() in _userExists() in
createUser()", style of fing.

I tried including a generic error object within the class, but it just adds
a level of indirection for very little benefit. Now I just have a $error
variable in every class, and a _setError() function to manipulate it (make
sure you set $error to false in the constructor, of course). This is from my
database class, hence the mysql_errno() catch.

/* add $s to the error string, and return false */
function _setError ($f, $l, $e = FALSE)
{
  if ($this->error === FALSE)
  {
    if ($m = @mysql_errno($this->_dbconn))
    {
      $m = "($m)";
    }
    $s = "Error: $e $m on line $l in function Database->$f()";
  } else {
    $s = ", on line $l in function Database->$f()";
  }
  $this->error = $this->error . $s;
  return (FALSE);
}

which can be called like this:

if (!is_int ($max))
{
  return ($this->_setError (__FUNCTION__, __LINE__, "invalid data '$max'"));
}

or like this

if ($this->error)
{
  return ($this->_setError (__FUNCTION__, __LINE__));
}

>This sound like good design? Any suggestions?

Whether it's good design or not... not particularly. But it's probably the
best you'll get without support for exceptions.

I should add that testing the error string makes more sense than testing the
return value of the function. Lets say you have a function that tests
whether a given user exists. It returns userid if the user is found, else
FALSE. How do you tell the difference between user-not-found and
database-crashed?

if (($userid = $db->userExists ($username)) == FALSE)
{
  if ($db->error)
  {
    /* there was an error */
    die ($db->error);
  } else {
    /* user was not found */
    $db->createUser ($username);
  }
} else {
  /* user found */
  echo ($userid);
}


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to