#30379 [Bgs]: Example of Exception $e is Incorrect
| From: | aidan@php.net | Date: | Mon, 11 Oct 2004 06:12:26 +0000 |
| Subject: | #30379 [Bgs]: Example of Exception $e is Incorrect | ||
| References: | 1 | Groups: | php.doc |
| Request: | Send a blank email to phpdoc+get-969364483@lists.php.net to get a copy of this message | ||
ID: 30379
Updated by: aidan@php.net
Reported By: hans at nyphp dot com
Status: Bogus
Bug Type: Documentation problem
Operating System: Irrelevant
PHP Version: Irrelevant
New Comment:
__toString has complicated (somewhat confusing) behaviour.
echo $e; // calls __toString
echo 'text', $e; // calls __toString
echo 'text'. $e; // doesn't call __toString
echo (string) $e; // doesn't call __toString
This is documented on the __toString page:
http://www.php.net/manual/en/language.oop5.magic.php
This behaviour may change in PHP 5.1
Also note: I've updated the exceptions page to call the getMessage
method, as it's more appropriate.
Previous Comments:
------------------------------------------------------------------------
[2004-10-10 18:21:02] hans at nyphp dot com
While the _toString() should be called, in PHP 5.0.2 echoing an object,
$e of class Exception, doesn't always call the _toString() method.
So perhaps this is more than a documentation problem. For example,
given this catch{} block:
catch( Exception $e ) {
$ref = new ReflectionObject($e);
echo var_export($ref->getMethods(),1);
echo "My Error: ".$e;
}
This outputs (shortended form):
array (
...
8 =>
class ReflectionMethod {
public $name = '__toString';
public $class = 'Exception';
},
)
My Error: Object id #3
H
------------------------------------------------------------------------
[2004-10-10 09:40:40] aidan@php.net
echo $e will call the exception classes __toString method. This will
show more information than just getMessage(). This isn't a mistake.
However, the docs are not very good - I'll have a look at them today.
------------------------------------------------------------------------
[2004-10-10 06:33:43] hans at nyphp dot com
Description:
------------
On the page that gives examples of how to use Exceptions:
http://www.php.net/manual/en/language.oop5.exceptions.php
The usage of catch() is incorrect in the examples. This code:
catch (Exception $e) {
echo "Caught exception: ", $e, "\n";
}
Would echo something like:
Caught exception: Object id #3
I cannot believe this is the desired output. This code:
catch (Exception $e) {
echo "Caught exception: ", $e->getMessage(), "\n";
}
Would provide the expected output:
Caught exception: Always throw this error
In other words, all exception code examples with echo statements of $e
should contain $e->getMessage() rather than just echoing $e.
Hans
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=30379&edit=1