为什么我们在PHP中使用assert()和assert_options()? [英] Why do we use assert() and assert_options() in PHP?

查看:107
本文介绍了为什么我们在PHP中使用assert()和assert_options()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是不熟悉PHP的人,现在正在阅读 php.net 上的文档来学习它-当前

请注意,所有这些选项都可以在您的 php.ini 文件中进行设置,以使它们始终有效-要更改的关键选项为 assert.active,assert.warning,assert.bail,assert.quiet_eval和assert_callback .

ASSERT_CALLBACK 是一个非常有用的选项,因为它允许您在代码未通过断言时编写错误处理程序.它使用断言失败时要执行的函数的字符串名称,并且您定义的函数必须采用三个参数-一个用于保存断言所在的文件,一个用于保存行,一个用于保存表达式.在回调函数中同时使用这三个函数,可以生成有意义的错误消息,可以轻松地对其进行调试.考虑以下代码片段:

 <?php函数assert_failed($ file,$ line,$ expr){打印在$ line行上$ file的断言失败:$ expr \ n";}assert_options(ASSERT_CALLBACK,'assert_failed');assert_options(ASSERT_WARNING,0);$ foo = 10;$ bar = 11;assert('$ foo> $ bar');?> 

参考: http://www.hackingwithphp.com/19/8/3/making-assertions


官方文档中的示例

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

示例#1 assert_options()示例

 <?php//这是我们要处理的函数//断言失败函数assert_failure(){回显声明失败";}//这是我们的测试功能函数test_assert($ parameter){断言(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,因此无法达到//是真实的回声从未到达";?> 

根据PHP文档 assert()

  1. 如果断言以字符串形式给出,则它将由 assert()评估为PHP代码.
  2. 如果将布尔条件作为断言传递,则此条件不会显示为您可能已通过 assert_options()定义的断言函数的参数.在调用之前,该条件会转换为字符串该处理程序函数,然后将布尔值FALSE转换为空字符串.
  3. 断言仅应用作 debugging 功能.您可以将它们用于完整性检查,以测试应该始终为TRUE的条件,如果条件不正确则表明某些编程错误,或者用于检查某些功能(例如扩展功能或某些系统限制和功能)的存在.
  4. 断言不应用于常规运行时操作,例如输入参数检查.根据经验,如果未激活断言检查,则您的代码应始终能够正常工作.
  5. assert()的行为可以通过 assert_options()或该功能手册页中所述的 .ini-settings 进行配置. assert_options()函数和/或 ASSERT_CALLBACK 配置指令允许将回调函数设置为处理失败的断言.6. assert()回调对于构建自动化测试套件特别有用,因为它使您可以轻松捕获传递给断言的代码以及断言的位置信息.虽然可以通过其他方法捕获此信息,但是使用断言可以使其更快,更轻松!

I am new to using PHP and am learning it by reading the documentation on php.net- currently the page for assert() to know about those assert() and assert_options() functions, but it does not explain why we use them and what these functions do in simple words. What do these functions and why do we use them in PHP?

解决方案

Assert() is a clever function that works along the same lines as our print statements, but they only have any effect if a certain condition is not matched. Essentially, assert() is used to say "This statement must be true - if it isn't, please tell me". Consider this following example:

<?php
    print "Stage 1\n";
    assert(1 == 1);
    print "Stage 2\n";
    assert(1 == 2);
    print "Stage 3\n";
?>

Here we have two assert()s, with the first call asserting that one must be equal to one, and the second call asserting that one must be equal to two. As it is impossible to redefine constants like 1 and 2, the first assert() will always evaluate to true, and the second will always evaluate to false. Here is the output from the script:

Stage 1 Stage 2 Warning: assert()

[http://www.php.net/function.assert]: Assertion failed in /home/paul/sandbox/php/assert.php on line 5

Stage 3

Note that the first assert() is not seen in the output at all because it evaluated to true, whereas the second assert() evaluated to false, so we get a warning about an assertion failure. Also note that we see "Stage 3" after the assertion failure warning, because the script carries on executing after the failure. As long as assertions evaluate to true, they have no effect on the running of the script, which means you can insert them for debugging purposes and not have to worry about taking them out once you are finished debugging.


If you are worried about your assertions slowing execution down, which, although the speed hit will be minimal, is still a valid concern, you can disable execution of assert() by using the assert_options() function or by setting assert.active to Off in your php.ini file. If you want to use assert_options(), it takes two parameters - the option to set and the value you wish to set it to - and there are a variety of ways it can make assert() more powerful.

Note that all of these options can be set in your php.ini file so that they are always in effect - the key options to change are assert.active, assert.warning, assert.bail, assert.quiet_eval, and assert_callback.

ASSERT_CALLBACK is a very useful options as it allows you to write an error handler for when your code fails an assertion. It takes the string name of a function to execute when assertions fail, and the function you define must take three parameters - one to hold the file where the assertion occurred, one to hold the line, and one to hold the expression. Using all three together in your callback function allows you to generate meaningful error messages that you can debug easily. Consider this code snippet:

<?php
    function assert_failed($file, $line, $expr) {
        print "Assertion failed in $file on line $line: $expr\n";
    }

    assert_options (ASSERT_CALLBACK, 'assert_failed');
    assert_options (ASSERT_WARNING, 0);

    $foo = 10;
    $bar = 11;
    assert('$foo > $bar');
?>

Ref: http://www.hackingwithphp.com/19/8/3/making-assertions


Example from official documentation

assert_options — Set/get the various assert flags

Example #1 assert_options() example

<?php
// This is our function to handle 
// assert failures
function assert_failure()
{
    echo 'Assert failed';
}

// This is our test function
function test_assert($parameter)
{
    assert(is_bool($parameter));
}

// Set our assert options
assert_options(ASSERT_ACTIVE,   true);
assert_options(ASSERT_BAIL,     true);
assert_options(ASSERT_WARNING,  false);
assert_options(ASSERT_CALLBACK, 'assert_failure');

// Make an assert that would fail
test_assert(1);

// This is never reached due to ASSERT_BAIL 
// being true
echo 'Never reached';
?>

As per PHP documentation assert()

  1. If the assertion is given as a string it will be evaluated as PHP code by assert().
  2. If you pass a boolean condition as assertion, this condition will not show up as parameter to the assertion function which you may have defined with assert_options().The condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.
  3. Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.
  4. Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.
  5. The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions. 6.assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

这篇关于为什么我们在PHP中使用assert()和assert_options()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆