note 115271 deleted from language.oop5.decon by cmb

From: Date: Mon, 07 Sep 2015 21:20:44 +0000
Subject: note 115271 deleted from language.oop5.decon by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-203729@lists.php.net to get a copy of this message
Note Submitter: mattsch at gmail dot com ---- 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'; } } ?>

« previous php.notes (#203729) next »