如果构造函数中的某些内容失败,如何防止进一步执行类

aWe*_*per 1 php oop constructor

如果构造函数中的某些内容失败,如何防止进一步执行类.

........Worker.php..............
class Worker {

    public function __construct() {

        try {               
            $this->pheanstalk   = new Pheanstalk('127.0.0.1');
        }
        catch (Exception $e) {
            logFatal('Pheanstalk: '.$e->getMessage());
        }
    }
    .............
    .............
    .............
    .............
}
Run Code Online (Sandbox Code Playgroud)

.

............processing.php..........
require_once ROOTPATH.'worker.php';

$worker = new worker();
$worker -> put($Data);
.............
.............
.............
.............
Run Code Online (Sandbox Code Playgroud)

现在,如果try块在构造函数中失败,我不想执行put()但其余的代码应继续在processing.php中

新的Pheanstalk('127.0.0.1'); 抛出一个由catch捕获的异常.

Wes*_*orp 5

最好的解决方案是在课堂外捕捉异常.你不仅可以跳过put,记录错误也不是那个类的责任.哦,单元测试也更容易!

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());
}
Run Code Online (Sandbox Code Playgroud)

如果它是抛出异常的另一个应用程序,并且您的构造函数被包围.考虑捕获异常,然后抛出自己的异常.