...

View Full Version : Resolved $e obj?



RonnyNishimoto
07-20-2012, 05:12 AM
Why did they use $e as the ojb? How would I know what letter I should use? What is the terminology for this variable? (Object variable?)
And why did they use "return $errorMsg;" instead of "echo $errorMsg;"?



class customException extends Exception {
public function errorMessage() {
$errorMsg = 'Error on line ' . $this->getLine() . ' in ' . $this->getFile() . ': <b>'
. $this->getMessage() . '</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new customException($email);
}
}
catch (customException $e) {
echo $e->errorMessage();
}
}

Fou-Lu
07-20-2012, 02:33 PM
$e is typically used when issuing a catch. It stands for $exception.
You can use anything you want, just don't overwrite anything in the meantime.

As for the return, that is required in order to issue it with the echo $e->errorMessage().
I wouldn't do that myself, I'd just pass the message off to the parent class to build, and if I want to display the line and file I'd invoke that information during the catch. To me I consider the stack trace for more valuable anyway.
A big part of exception handling is when the application is given something, it determines something is not right, but doesn't know how to deal with it. So you throw an exception as a way for the underlying code to say I don't know what to do with it, so you deal with it. In this aspect, many of your exceptions need no body at all.


class NotOwnerException extends RuntimeException
{
}

class LastOwnerException extends RuntimeException
{
}

//...
public function removeOwner($toRemove, $authorizedBy)
{
if (!$this->isOwner($authorizedBy))
{
throw new NotOwnerException();
}
if (count($this->getOwners()) <= 1)
{
throw new LastOwnerException();
}
//. . .
}

try
{
$acl->removeOwner($toRemove, $authorizedBy);
}
catch (NotOwnerException $ex)
{
print 'You are not an owner.';
}
catch (LastOwnerException $ex)
{
print 'You cannot remove the last owner.';
}

For example. I typically only use messages if its ambiguous, so if instead I throw InvalidArgumentException for both scenarios, I'd add a message to indicate which argument threw the error.

RonnyNishimoto
07-20-2012, 07:40 PM
Confusing but I understand better haha. I got an error for some reason when I tried changing both the $e's, but now it works for some reason. Thanks fou!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum