Home >Backend Development >PHP Problem >What is a PHP assertion? How to use it?

What is a PHP assertion? How to use it?

王林
王林forward
2019-08-29 15:46:257990browse

Assertions in PHP are often used for debugging to check whether an expression or statement is FALSE. This article will take you to re-understand the power of the PHP assert() function.

This article is based on PHP Version 7.1.28

1. What is an assertion

When writing a program, certain assumptions are often made. The assertion is used to capture hypothetical exceptions. We can also think of assertions as a special form of exceptions.

Assertions are generally used to judge the program execution structure and cannot be used to process business processes. The most commonly used scenario is unit testing, and general unit testing frameworks use assertions.

assert(1 == 2);
// 运行结果:
// Warning: assert(): assert(1 == 2) failed in /Users/shocker/Desktop/demo.php on line 25

2. Assertions in PHP

In PHP, the assert() function is used to assert expressions.

// PHP 5assert ( mixed $assertion [, string $description ] ) : bool
// PHP 7assert ( mixed $assertion [, Throwable $exception ] ) : bool

4. Traditional assertion method

Parameter assertion supports both expressions and expression strings (some It will be used in specific scenarios, such as determining whether a string expression is legal)

If assertion is a string, it will be executed as PHP code by assert(). The advantage of assertion being a string is that it is less expensive when assertions are disabled, and the message will contain the assertion expression when the assertion fails.

Assert this feature should only be used for debugging. You should use it for sanity checks to test whether a condition should always be TRUE, to indicate some program error, or to check for the presence of specific functionality (like extension functions or specific system limitations and capabilities).

Assertions should not be used for normal runtime operations, such as input parameter checking. As a rule of thumb, your code should also run correctly when assertions are disabled.

Example:

function my_assert_handler($file, $line, $code, $desc){    echo "Assertion Failed:
    File '{$file}'
    Line '{$line}'
    Code '{$code}'
    Desc '{$desc}'
";
}
// 设置回调函数
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// 让一则断言失败
assert('1 == 2', '1 不可能等于 2');

Run result:

Assertion Failed:
    File '/Users/shocker/Desktop/demo.php'
    Line '29'
    Code '1 == 2'
    Desc '1 不可能等于 2'

5. Support exception assertion

In PHP 7 , assert() is a language structure that allows different measures to take effect in different environments. For details, see zend.assertions configuration.

In addition, it also supports capturing errors through AssertionError .

Usage example:

assert_options(ASSERT_EXCEPTION, 1); 
// 在断言失败时产生异常
try {    
// 用 AssertionError 异常替代普通字符串
    assert(true == false, new AssertionError('True is not false!'));
} catch (Throwable $e) {    
echo $e->getMessage();
}

Run result:

True is not false!

6. Control assertion behavior

PHP supports assert_options() The function configures the assertion, and you can also use ini to set it

In the following configuration, the constant flag is used for the assert_options() function to configure, and the ini setting is used for the ini_set() function setting, the effect is the same

What is a PHP assertion? How to use it?

zend.assertions is a special configuration (supported by PHP >= 7.0.0) that controls the behavior of assertions in different operating environments and can only be set with ini_set(). Moreover, if it is set to 1, it cannot be set to -1, and vice versa. Others are not restricted.

1: Compile the code and execute it (development mode)

0: Edit the code, but skip it when running

-1: Do not compile the code (production mode)

7. Version incompatibility

PHP >= 5.4.8, description can be provided as the fourth parameter to ASSERT_CALLBACK mode Callback function

In PHP 5, the parameter assertion must be an executable string, or an expression whose result is a Boolean value

In PHP 7, the parameter assertion can be any expression , and use its operation results as the basis for assertion

In PHP 7, the parameter exception can be a Throwable object, which is used to capture expression run errors or assertion results that fail. (Of course assert.exception needs to be turned on)

PHP >= 7.0.0, supports zend.assertions, assert.exception related configurations and features

PHP >= Starting from version 7.2, parameters Assertion no longer supports string

Deprecated: assert(): Calling assert() with a string argument is deprecated

8. Application scenarios

Debug output:

Look at the example first:

assert('1 == 2', '1 不可能等于 2');

Run Result:

Warning: assert(): 1 不可能等于 2: "1 == 2" failed in /Users/shocker/Desktop/demo.php on line 10

Similar to:

$expression = 1 == 2;
if (!($expression)) {
    echo "1 不可能等于 2\n";
    var_dump($expression);
    echo __FILE__ . "\n";
}

However, we cannot know the specific expression of $expression, nor the specific number of execution lines.

9. Unit test

function arraySum(array $nums) {
    $sum = 0;    foreach ($nums as $n) {
        $sum += $n;
    }    return $sum;
}

assert(arraySum([1, 2, 3]) == 6, 'arraySum() 测试不通过:');
assert(is_numeric(arraySum([1, 2, 3])), 'arraySum() 测试不通过:');

10. Verification expression

Tip:

## Starting with #PHP 7, a new Error class has been added to capture PHP built-in errors, including syntax errors. Error and the previous Exception both inherit from Throwable, so starting from 7.0.0, Throwable can catch all errors and exceptions.

The following example demonstrates how to verify whether a string expression is a legal PHP expression:

try {
    assert('a +== 1');
} catch (Throwable $e) {    
    echo $e->getMessage(), "\n";
}

Running result:


Failure evaluating code: 
a +== 1

ten 1. Security issues

What will be the result if the following code is used?

function demo(){
    file_put_contents('data.log', 'shockerli.net');
    return true;
}

$func = $_GET["func"];
assert("$func()");

所以,对于 assert 函数,正常情况下是不建议用于生产环境的。

与 eval 一样会执行任何 PHP 代码,危害极大。这也是 PHP 从 7.2 开始废弃支持字符串表达式的原因

感谢您的阅读,如有错误请指出。

相了解更多相关问题请访问PHP中文网:PHP视频教程

The above is the detailed content of What is a PHP assertion? How to use it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete