问题描述:

I'm new to PHP and was browsing php.net, where I came across this piece of code:

<?php

function inverse($x) {

if (!$x) {

throw new Exception('Division by zero.');

}

return 1/$x;

}

try {

echo inverse(5) . "\n";

echo inverse(0) . "\n";

} catch (Exception $e) {

echo 'Caught exception: ', $e->getMessage(), "\n";

}

// Continue execution

echo "Hello World\n";

?>

What exactly is $e? Can it be renamed? What does it do? Why do we need it?

网友答案:

It's simply a variable, you can call it whatever you want. Basically the variable points to the Exception-object, and it's conventionally called $e as "e" is short for Exception.

Also, when using Exceptions, it's a good idea to create your own Exception-classes by just creating a new class that extends Exception. For example:

<?php

class AuthException extends Exception {}

class SuspendedException extends Exception {}

In this case, you can throw new AuthException() should a user fail to authenticate. On the other hand, if a user manages to login but is suspended from your page, you can throw new SuspendedException().

This way you can extend your try-catch-blocks to catch different exceptions and handle them differently.

<?php

try {
    //logging your user in
} catch (AuthException $ae) {
    //handle an unauthorized user
} catch (SuspendedException $se) {
    //handle a suspended user
}

Notice how I'm using $ae and $se rather than a plain $e - as I said earlier, those are only variables and can be named whatever you like. Just try to stay consistent with your code.

网友答案:

$e is a variable that holds an Exception object, so yes you can rename it. What it does is that if there is some exception in your try-block then the catch-block runs, so there you can fetch the exception, maybe log it, try something else or print an useful error to the user.

http://php.net/manual/en/language.exceptions.php

网友答案:

It can be renamed, to any legal php variabe name. and has the message and related info to the exception happened. just simply make it var_dump to see information

相关阅读:
Top