【问题标题】:How to prevent further execution of class if something fails in constructor如果构造函数中出现问题,如何防止进一步执行类
【发布时间】:2012-03-29 13:59:33
【问题描述】:

如果构造函数失败,如何防止类的进一步执行。

........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);
.............
.............
.............
.............

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

new Pheanstalk('127.0.0.1');抛出一个被 catch 捕获的异常。

【问题讨论】:

    标签: php oop constructor


    【解决方案1】:

    最好的解决方案是在你的班级之外捕获异常。您不仅可以跳过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());
    }
    

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

    【讨论】:

    • 新 Pheanstalk('127.0.0.1');抛出一个当前被 catch 捕获的异常,所以你想让我做什么改变
    • 我在帖子底部添加了更多解释。如果你的类是一个包装器,我会捕捉并抛出我自己的异常。并且仍然遵循最初的解决方案。
    【解决方案2】:

    为什么不在构造函数中抛出异常呢? 见http://php.net/manual/en/language.exceptions.php

    【讨论】:

      猜你喜欢
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多