Why do we use assert () and assert_options () in PHP?

I am new to using PHP and learning it by reading the documentation on php.net - currently the assert () page to learn about those assert () and assert_options () functions , but that doesn't explain why we use them and what these functions are make simple words. What do these functions mean and why do we use them in PHP?

+6
source share
2 answers

Assert()is a smart function that works in the same way as our print operators, but they have any effect only if a certain condition does not meet. Essentially, assert()used to say: "This statement must be true - if it is not, please tell me." Consider the 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()with the first call stating that one must be equal to one, and the second call stating that one must be equal to two. Since it is not possible to override constants such as 1 and 2, the first assert()will always be true, and the second will always be false. Here is the script output:

Stage 1 Stage 2 Warning: assert ()

[ http://www.php.net/function.assert]: /home/paul/sandbox/php/assert.php 5

3

, assert() , true, assert() false, warning assertion failure. , "Stage 3" failure warning , . , , , .


, , , , , assert() assert_options() assert.active Off. php.ini. assert_options(), - , - assert() . enter image description here

, php.ini - , : assert.active, assert.warning, assert.bail, assert.quiet_eval, and assert_callback.

ASSERT_CALLBACK - , , . , - , , . , . :

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

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


assert_options - / assert

# 1 assert_options()

<?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';
?>

PHP assert()

  1. , PHP- assert().
  2. , , , , assert_options(). -, FALSE .
  3. Assertions debugging. , , , , , , .
  4. Assertions , input parameter. , , .
  5. assert() assert_options() .ini-settings . assert_options() / ASSERT_CALLBACK . 6. assert() , , , , . , !
+8

assert() - , . Paul Hudson:

, assert() , : " , , , ".

, assert_options(ASSERT_ACTIVE), assert_options() , , , ( , PHP script , , , / ..). parameters .

.

.

+4

All Articles