这是正确的实施方式吗;“按合同设计”;PHP中的模式?

这是正确的实施方式吗;“按合同设计”;PHP中的模式?,php,design-patterns,datacontract,Php,Design Patterns,Datacontract,我发现了“契约式设计”模式以及如何在PHP中实现。我找不到一个真实的例子来说明如何在PHP中实现这一点第一个问题是我的做法是否正确第二个是为什么不尊重断言回调 用于可重用断言的静态类断言: class Asserts { public static function absentOrNotNumeric($value) { return !isset($value) ? true : is_numeric($value); } } 用法: assert_

我发现了“契约式设计”模式以及如何在PHP中实现。我找不到一个真实的例子来说明如何在PHP中实现这一点第一个问题是我的做法是否正确第二个是为什么不尊重断言回调

用于可重用断言的静态类
断言

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)”失败

您的代码:

我的代码:


尝试使用双引号:
assert(“Asserts::absentOrNotNumeric($value)”

正在引发您的异常,将其更改为:

public static function onAssertFailure($file, $line, $message)
{
    echo "<hr>Assertion Failed:
    File '$file'<br />
    Line '$line'<br />
    Code '$code'<br /><hr />";
}
异常将被抛出,因此它似乎在抛出异常之前停止执行


希望这有帮助

它会触发什么警告?@Mario请看我的编辑,谢谢。同样,不,
assert
需要单引号,请参见PHP网站上的示例。
assert_options(ASSERT_BAIL,     false);