我试图自己做这件事,并找到了一个似乎可行的解决方案。
为了回应其他试图通过告诉提问者使用不同的解决方案来回答问题的人,我还将尝试解释问题的原因。原始海报或我都不想使用异常,因为重点不是使用异常处理功能,而是将负担放在我们使用此类的任何代码上。至少对我而言,重点是能够使用它在可能以非面向对象或非基于异常的样式编写的其他 PHP 代码中无缝地类。许多内置 PHP 函数的编写方式使得不成功进程的结果为 false 是可取的。同时,我们可能希望能够在我们自己的代码中以一种特殊的方式处理这个对象。
例如,我们可能想做类似的事情:
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。