note 115271 added to language.oop5.decon

From: Date: Wed, 25 Jun 2014 14:35:28 +0000
Subject: note 115271 added to language.oop5.decon
Groups: php.notes 
Request: Send a blank email to php-notes+get-199762@lists.php.net to get a copy of this message
I would advise against the use of exceptions within __construct. If you store the error code for an exception within a function of that class, you have no way of reading that error code to tell what type of exception it is because the object does not exist yet. Checking the code cannot be accomplished if an exception is thrown in the construct: <?php class FooException extends Exception { } class Foo { private $bar; private $baz; public function __construct($foo = null) { if ($foo === null) { throw new FooException('An error occured in construct', $this->errorConstruct()); } } public function setBar() { $this->bar = 'baz'; } public function setBaz() { $this->baz = 'foo'; } final public function errorFooNotSet() { return 1; } } try { $foo = new Foo(); $foo->setBar(); $foo->setBaz(); } catch (FooException $e) { // This will error because the object doesn't exist yet if ($e->getCode() == $foo->errorFooNotSet()) { echo 'foo is not set'; } } ?> Checking the code can be accomplished if an exception is not thrown in the construct: <?php class FooException extends Exception { } class Foo { private $bar; private $baz; public function __construct($foo = null) { } public function init() { if ($foo === null) { throw new FooException('An error occured in construct', $this->errorConstruct()); } } public function setBar() { $this->init(); $this->bar = 'baz'; } public function setBaz() { $this->init(); $this->baz = 'foo'; } final public function errorFooNotSet() { return 1; } } try { $foo = new Foo(); $foo->setBar(); $foo->setBaz(); } catch (FooException $e) { // This will work because the object does exist if ($e->getCode() == $foo->errorFooNotSet()) { echo 'foo is not set'; } } ?> ---- Server IP: 216.194.115.244 Probable Submitter: 130.80.28.6 ---- Manual Page -- http://php.net/manual/en/language.oop5.decon.php Edit -- https://master.php.net/note/edit/115271 Del: integrated -- https://master.php.net/note/delete/115271/integrated Del: useless -- https://master.php.net/note/delete/115271/useless Del: bad code -- https://master.php.net/note/delete/115271/bad+code Del: spam -- https://master.php.net/note/delete/115271/spam Del: non-english -- https://master.php.net/note/delete/115271/non-english Del: in docs -- https://master.php.net/note/delete/115271/in+docs Del: other reasons-- https://master.php.net/note/delete/115271 Reject -- https://master.php.net/note/reject/115271 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199762) next »