Is this the right way to implement the Design by Contract template in PHP?

I discovered the Design by Contract template and how to implement it in PHP. I can not find a real example of how to do this in PHP. First question Am I doing this right? The second is why the assert call is not being made?

Static class Assertsfor reusable statements:

class Asserts
{
    public static function absentOrNotNumeric($value)
    {
        return !isset($value) ? true : is_numeric($value);
    }
}

Using:

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.');

Only a (correct) warning is triggered:

Warning: assert () [function.assert]: The statement "Asserts :: absetOrNotNumeric ($ value)" failed.

+5
source share
2 answers

, :

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);

, , .

,

+4

: http://codepad.org/y10BlV8m

: http://codepad.org/slSX3HKd

: assert("Asserts::absentOrNotNumeric($value)");

-1

All Articles