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

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

问题描述

我是使用 PHP 的新手,正在通过阅读 php.net 上的文档来学习它 - 目前是 assert() 以了解那些 assert()assert_options() 函数,但它没有用简单的语言解释为什么我们使用它们以及这些函数的作用.这些函数有什么作用?我们为什么要在 PHP 中使用它们?

解决方案

Assert() 是一个聪明的函数,它的工作原理与我们的打印语句相同,但它们只有在某些条件不匹配.本质上,assert() 用于表示此陈述必须为真 - 如果不是,请告诉我".考虑以下示例:

这里我们有两个assert(),第一个调用断言一个必须等​​于一,第二个调用断言一个必须等​​于二.由于不可能重新定义像 1 和 2 这样的常量,第一个 assert() 将始终评估为真,而第二个将始终评估为假.这是脚本的输出:

<块引用>

第一阶段第二阶段警告:assert()

[

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

ASSERT_CALLBACK 是一个非常有用的选项,因为它允许您在代码断言失败时编写错误处理程序.当断言失败时,它需要一个函数的字符串名称来执行,你定义的函数必须接受三个参数——一个保存发生断言的文件,一个保存行,一个保存表达式.在回调函数中同时使用这三者可以让您生成有意义的错误消息,您可以轻松调试.考虑这个代码片段:

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

<小时>

来自官方文档的示例

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

示例 #1 assert_options() 示例

根据 PHP 文档 assert()

  1. 如果断言以字符串形式给出,assert() 会将其评估为 PHP 代码.
  2. 如果您将布尔条件作为断言传递,则此条件将不会作为您可能已使用 assert_options() 定义的断言函数的参数显示.在调用之前,条件将转换为字符串处理函数,布尔值 FALSE 被转换为空字符串.
  3. Assertions 应仅用作 debugging 功能.您可以将它们用于完整性检查,以测试应始终为 TRUE 的条件,如果不是,则指示一些编程错误,或者检查是否存在某些功能,例如扩展功能或某些系统限制和功能.
  4. Assertions 不应用于像 input parameter 检查这样的正常运行时操作.根据经验,如果未激活断言检查,您的代码应该始终能够正常工作.
  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
";
    assert(1 == 1);
    print "Stage 2
";
    assert(1 == 2);
    print "Stage 3
";
?>

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
";
    }

    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天全站免登陆