我有一个objet,我想在抛出异常时重置,有没有办法做到这一点?
例如我有这个课程:
class TestClass{
public $value = 0;
}
然后我创建了一个类的实例,并在$value
中将它try
设置为100,然后抛出这样的错误:
$test = new TestClass();
try{
$test->value = 100;
throw new Exception("Error!", 100);
}catch(Exception $ex){
var_dump($test);
}
因为抛出错误,将调用var_dump
,但是当转储显示时,$value
仍然是100
我希望它仍然是0
对于这个测试,但事实并非如此。有没有办法在抛出错误时重置实例?
答案 0 :(得分:0)
我看到的最简洁的方法是使用reset()
方法,并在异常处理程序中调用它。
try{
$test->value = 100;
throw new Exception("Error!", 100);
}catch(Exception $ex){
$test->reset();
var_dump($test);
}
我不知道你怎么能以一般的方式做到这一点。你也可以这样做;
class TestClass {
// ....
public function reset() {
// ....
}
public function tryToDoSomething($x) {
try {
// something with $x that might throw
} catch (Exception $x) {
$this->reset();
}
}
}
答案 1 :(得分:0)
注意:自从写这篇文章后我的意见发生了变化。对象的原始值不是为了保持 - 这是为了实现使用对象来决定 - 这可能会根据项目的使用位置而改变。另一种方法是为工厂中的对象设置该值;允许多个工厂用于不同的场景。
“我有一个对象,我想在抛出异常时重置,有没有办法做到这一点?”
是的,您需要说明要返回的原始值。这是班级constant的完美候选人,但如果您愿意,可以将其设置在另一个变量中。我将使用类常量。
class TestClass
{
const RESET_VAL = 100;
/**
* @var int The object's value
*/
protected $value = 100;
/**
* @param mixed $value
*/
public function setValue($value)
{
$this->value = $value;
}
/**
* Reset $value back to it's initial state
*
* @see self::RESET_VAL
*/
public function resetValue()
{
$this->value = self::RESET_VAL;
}
}
这里有什么改变,为什么?好吧,不要使用public
作为access modifier!为什么?因为你不是在这里写'c-style'结构。只要您拥有公共财产,您就会将全局州引入您的申请中。你应该有方法,比如setValue()
,以便改变对象的状态。
还有resetValue()
方法。我们为什么要使用它,而不是仅仅调用$testClass->resetValue(TestClass::RESET_VAL);
?好吧,因为那不是面向对象的编程 - 在对象上调用方法是。
您的最终代码如下所示,使用上述类:
$test = new TestObject;
try
{
$test->setValue(55);
/** Somewhere down the object chain you get an exception... **/
throw new Exception("Uh oh...");
}
catch (Exception $e)
{
$test->resetValue();
}