"계약에 의한 디자인"패턴과 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)"이 (가) 실패했습니다.
어떤 경고가 발생합니까? –
@Mario 내 수정 사항을 확인합니다. 감사합니다. – gremo