【发布时间】:2011-11-28 14:33:27
【问题描述】:
我发现了“按合同设计”模式以及如何在 PHP 中实现。我找不到如何在 PHP 中执行此操作的真实示例。 第一个问题是我做对了吗? 第二个是为什么assert回调不被兑现?
用于可重用断言的静态类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)”失败。
【问题讨论】:
-
它会触发什么警告?
-
@Mario 看到我的编辑,谢谢。
标签: php design-patterns datacontract