我試圖在此做我自己,發現似乎工作的解決方案。
爲了迴應其他人試圖通過告訴提問者使用不同的解決方案來回答問題,我也會嘗試解釋問題的原因。無論是原始海報還是我想要使用異常,因爲重點不是使用異常處理功能,而是將這種負擔放在我們使用這個類的任何代碼上。至少對我而言,這一點是能夠使用這個無縫地在其他PHP代碼中編寫,這些代碼可以用非面向對象或非基於異常的風格編寫。許多內置的PHP函數都是以這樣的方式編寫的,以致對於不成功的進程來說錯誤的結果是可取的。同時,我們可能希望能夠在我們自己的代碼中以特殊的方式處理這個對象。
例如,我們可能想要做這樣的事情:
if (!($goodObject = ObjectFactory::getObject($objectType))) {
// if $objectType was not something ObjectFactory could handle, it
// might return a Special Case object such as FalseObject below
// (see Patterns of Enterprise Application Architecture)
// in order to indicate something went wrong.
// (Because it is easy to do it this way.)
//
// FalseObject could have methods for displaying error information.
}
這裏是一個非常簡單的實現。
class FalseObject {
public function __toString() {
// return an empty string that in PHP evaluates to false
return '';
}
}
$false = new FalseObject();
if ($false) {
print $false . ' is false.';
} else {
print $false . ' is true.';
}
print '<br />';
if (!$false) {
print $false . ' is really true.';
} else {
print $false . ' is really false.';
}
//我打印$ false只是爲了確保沒有意外的事情發生。
的輸出是:
是假的。 確實是錯誤的。
我測試過這一點,如果你有這個類裏面的一些聲明的變量,如它的工作原理,甚至:
class FalseObject {
const flag = true;
public $message = 'a message';
public function __toString() {
return '';
}
}
稍微更有趣的實現可能是:
class FalseException extends Exception {
final public function __toString() {
return '';
}
}
class CustomException extends FalseException { }
$false = new CustomException('Something went wrong.');
使用與以前相同的測試代碼,$ false評估爲false。
你們錯過了這個問題的關鍵。異常是使用錯誤的對象。將其更改爲「結果」或其他。這一點與此無關,只是「在if語句中可以使對象返回false」 – Ethan 2009-07-25 00:28:57
嘿大家,因爲我愚蠢地說了我的問題,我在這裏問了我的問題:http:///stackoverflow.com/questions/1182710/is-it-possible-to-make-an-object-return-false-by-default 感謝那些幫助。 – Ethan 2009-07-25 18:42:25