略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: assert_options

2024-04-28

assert_options

(PHP 4, PHP 5, PHP 7, PHP 8)

assert_options设置/获取断言的各种标志

说明

assert_options(int $what, mixed $value = ?): mixed

设置 assert() 的各种控制选项,或者是仅仅查询当前的设置。

参数

what

断言标志
标志 INI 设置 默认值 描述
ASSERT_ACTIVE assert.active 1 启用 assert() 断言
ASSERT_WARNING assert.warning 1 为每个失败的断言产生一个 PHP 警告(warning)
ASSERT_BAIL assert.bail 0 在断言失败时中止执行
ASSERT_QUIET_EVAL assert.quiet_eval 0 在断言表达式求值时禁用 error_reporting
ASSERT_CALLBACK assert.callback (null) 断言失败时调用回调函数
value

标志的新值。

返回值

返回任意标志的原始设置,出错时返回 false

范例

示例 #1 assert_options() 例子

<?php
// 处理断言失败时的函数
function assert_failure()
{
    echo 
'Assert failed';
}

// 我们的测试函数
function test_assert($parameter)
{
    
assert(is_bool($parameter));
}

// 设置断言标志
assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  false);
assert_options(ASSERT_CALLBACK'assert_failure');

// 让一个断言会失败
test_assert(1);

// 由于 ASSERT_BAIL 是 true,这里永远也到不了
echo 'Never reached';
?>

参见

  • assert() - 检查一个断言是否为 false
add a noteadd a note

User Contributed Notes 1 note

up
2
18 years ago
Here is an exemple how to use the assertion callback function :

<?php
  assert_options
( ASSERT_CALLBACK, 'assert_callback');

  function
assert_callback( $script, $line, $message ) {
    echo
'You have a design error in your script <b>', $script,'</b> : line <b>', $line,'</b> :<br />';
    echo
'<b>', ereg_replace( '^.*//\*', '', $message ), '</b><br /><br />';
    echo
'Open the source file and check it, because it\'s not a normal behaviour !';
    exit;
  }

 
$x = 3;
 
assert('is_integer( $x ) && ($x >= 0) && ($x <= 10); //* $x must be an integer value from 0 to 10' );
  echo
"0 <= $x <= 10";
?>

assertion is usefull for "design by contract" methodology ...

官方地址:https://www.php.net/manual/en/function.assert-options.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3