How to use assertion function in PHP
This article will introduce to you how to use the assertion function in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
I originally thought that the assertion-related functions were provided by PHPUnit and these unit test components. After reading the manual, I discovered that the assert() assertion function comes with PHP itself. a function of. In other words, when we perform simple tests in the code, we do not need to completely introduce the entire unit test component.
assert() assertion function
1 2 3 4 5 |
|
Obviously, the second piece of code cannot pass assertion verification. At this time, PHP will return a warning or exception error. Why are there two possible error forms? When we set assert.exception in php.ini to off or 0, that is, when we turn off the ability of this parameter, the program will still return a warning in the form of PHP5, just like the comment in the code above.
At the same time, exceptions cannot be captured through try...catch. This parameter actually controls whether to throw an authentic exception object. If you keep this parameter as the default, that is, set to on or 1, an exception will be thrown directly and the program will terminate.
As can be seen from the above code, the first parameter of the assertion is an expression, and it requires an expression that returns a bool type object. What if we pass a string or a number?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Obviously, the expression of the first parameter will be type casted, but the string type will have an obsolete reminder, indicating that the expression type of the string type passed to the assert() function is obsolete. . The current test version is 7.3. In the future, errors or exceptions that terminate the operation may be directly reported.
The main problem is that if the passed string itself is also an expression, the judgment will be based on the content of this expression, which can easily lead to ambiguity, just like the last piece of code. Of course, the outdated usage method is still not recommended. Here is just an understanding.
Next let’s take a look at the other parameters of the assert() function. Its second parameter is of two types, either a string used to define error information, or an exception class used to throw Exception occurred.
1 2 3 4 |
|
If a string is given directly, then the content of the error message we defined will be displayed in the warning message. This is very easy to understand.
1 2 3 4 5 6 7 |
|
Of course, we can also give an exception class to let the assertion throw an exception. By default, the throwing of this exception will abort the execution of the program. That is a normal exception throwing process. We can use try...catch to catch exceptions.
1 2 3 4 5 6 |
|
There is another parameter that will affect the overall operation of assertions, that is the zend.assertions parameter in php.ini. It contains three values:
- 1, which generates and executes the code. Generally,
- 0 is used in the test environment. The code is generated but will pass through
- - during runtime. 1. No code is generated. Generally,
is used in the formal environment. You can configure the test by yourself. The default value in the default php.ini is 1, which is the normal execution of the assert() function. .
assert_options() and the corresponding parameter configuration in php.ini
The assertion function in PHP also provides us with an assert_options() function for Conveniently set and obtain some parameter configurations related to assertion capabilities. The assertion flags it can set include:
Flags | INI Settings | Default Value | Description
- ##ASSERT_ACTIVEassert.active1Enable assert() assertionASSERT_WARNINGassert.warning 1Generate a PHP warning for each failed assertionASSERT_BAILassert.bail0Abort execution on assertion failureASSERT_QUIET_EVALassert.quiet_eval0In assertion expression Disable error_reporting when evaluatingASSERT_CALLBACKassert.callback(NULL)Callback function called when assertion fails
这些参数的含义都非常好理解,大家可以自己测试一下。我们就来看一下最后一个 ASSERT_CALLBACK 的作用。其实它的说明也非常清楚,就是断言失败的情况下就进入到这个选项定义的回调函数中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 1);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK,
function
(
$params
){
echo
"====faild===="
, PHP_EOL;
var_dump(
$params
);
echo
"====faild===="
, PHP_EOL;
});
assert(1!=1);
// ====faild====
// string(105) ".../source/一起学习PHP中断言函数的使用.php"
// ====faild====
Copy after login当断言失败的时候,我们就进入了回调函数中,在回调函数直接简单的打印了传给回调函数的参数内容。可以看出,这个回调函数里面传递过来的是无法通过断言的文件信息。
总结
学习掌握一下断言函数的使用及配置,可以为我们将来学习 PHPUnit 单元测试打下基础,当然,本身这个能力的东西就不是很多,大家记住就好啦!
测试代码:
1
https:
//github.com/zhangyue0503/dev-blog/blob/master/php/202005/source/%E4%B8%80%E8%B5%B7%E5%AD%A6%E4%B9%A0PHP%E4%B8%AD%E6%96%AD%E8%A8%80%E5%87%BD%E6%95%B0%E7%9A%84%E4%BD%BF%E7%94%A8.php
Copy after login推荐学习:php视频教程
The above is the detailed content of How to use assertion function in PHP. For more information, please follow other related articles on the PHP Chinese website!
Statement of this WebsiteThe content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cnHot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Assassin's Creed Shadows: Seashell Riddle Solution3 weeks ago By DDDWhat's New in Windows 11 KB5054979 & How to Fix Update Issues2 weeks ago By DDDWhere to find the Crane Control Keycard in Atomfall3 weeks ago By DDDRoblox: Dead Rails - How To Complete Every Challenge4 weeks ago By DDDAtomfall guide: item locations, quest guides, and tips4 weeks ago By DDDHot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
CakePHP Tutorial1392
52
nyt mini crossword answers36
110
PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM
PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati
7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM
If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op
How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM
Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM
JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,
How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM
This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an
PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM
A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total
Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM
Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM
What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.