我发现了“按合同设计”模式以及如何在PHP中实现。我无法在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()[function.assert]:断言 “Asserts :: absetOrNotNumeric($ value)”失败。
答案 0 :(得分:4)
您的异常被抛出,将其改为:
public static function onAssertFailure($file, $line, $message)
{
echo "<hr>Assertion Failed:
File '$file'<br />
Line '$line'<br />
Code '$code'<br /><hr />";
}
导致显示文本,某些测试发现如果您更改此选项
assert_options(ASSERT_BAIL, false);
将抛出异常,因此它似乎在抛出异常之前执行失败。
希望有所帮助
答案 1 :(得分:-1)
您的代码:http://codepad.org/y10BlV8m
我的代码:http://codepad.org/slSX3HKd
尝试使用双引号:assert("Asserts::absentOrNotNumeric($value)");