How to prevent further execution of class if something fails in constructor.
........Worker.php..............
class Worker {
public function __construct() {
try {
$this->pheanstalk = new Pheanstalk('127.0.0.1');
}
catch (Exception $e) {
logFatal('Pheanstalk: '.$e->getMessage());
}
}
.............
.............
.............
.............
}
.
............processing.php..........
require_once ROOTPATH.'worker.php';
$worker = new worker();
$worker -> put($Data);
.............
.............
.............
.............
Now if the try block fails in the constructor i dont want to execute put() but rest of code should continue in processing.php
new Pheanstalk('127.0.0.1'); throws a exception which is caught by catch.
Best solution is to catch the exception outside your class. Not only can you skip the put
, logging errors is also not really the responsibility of that class anyway. Oh and Unit testing is easier too!
class SomeClass
{
public function __construct()
{
if ($somethingFails === true)
throw new Exception();
}
}
try {
$instance = new SomeClass();
$instance->put();
} catch (Exception $exception) {
// Handle here
logFatal('Pheanstalk: '.$e->getMessage());
}
If it's another piece of application throwing the exception, and your constructor is wrapped around it. Consider catching the exception, and then throwing your own.
Why don't you throw an exception in the constructor? See http://php.net/manual/en/language.exceptions.php