我發現了「按合同設計」模式以及如何在PHP中實現。我找不到如何在PHP中執行此操作的真實世界示例。 第一個問題是我在正確的方式嗎? 第二個是爲什麼assert回調沒有兌現?這是在PHP中實現「按合同設計」模式的正確方法嗎?
可重複使用的斷言靜態類Asserts
:
class Asserts
{
public static function absentOrNotNumeric($value)
{
return !isset($value) ? true : is_numeric($value);
}
}
用法:
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_WARNING, true);
assert_options(ASSERT_CALLBACK, array('UseAsserts', 'onAssertFailure'));
class UseAsserts
{
private $value;
public function __construct($value)
{
// Single quotes are needed otherwise you'll get a
// Parse error: syntax error, unexpected T_STRING
assert('Asserts::absentOrNotNumeric($value)');
$this->value = $value;
}
public static function onAssertFailure($file, $line, $message)
{
throw new Exception($message);
}
}
// This will trigger a warning and stops execution, but Exception is not thrown
$fail = new UseAsserts('Should fail.');
只(右)警告被觸發:
警告:斷言()函數.assert]:聲明 「Asserts :: absetOrNotNumeric($ value)」失敗。
它會觸發什麼警告? – 2011-11-28 14:49:55
@Mario查看我的編輯,謝謝。 – gremo