search
HomeBackend DevelopmentPHP TutorialA brief discussion on the usage of assertion functions in PHP

This article will teach you how to use assertion functions in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the usage of assertion functions in PHP

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

assert(1==1);

assert(1==2);
// assert.exception = 0 时,Warning: assert(): assert(1 == 2)
// assert.exception = 1 时,Fatal error: Uncaught AssertionError: 验证不通过

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 caught 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?

// 设置 assert.exception = 0 进行多条测试

assert(" ");
// Deprecated: assert(): Calling assert() with a string argument is deprecated
// Warning: assert(): Assertion " " failed

assert("1");
// Deprecated: assert(): Calling assert() with a string argument is deprecated

assert(0);
// Warning: assert(): assert(0) failed

assert(1);

assert("1==2");
// Deprecated: assert(): Calling assert() with a string argument is deprecated
// Warning: assert(): Assertion "1==2" failed

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.

assert(1==1, "验证不通过");

assert(1==2, "验证不通过");
// Warning: assert(): 验证不通过 failed

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.

// 注意 assert.exception 设置不同的区别

assert(1==1,  new Exception("验证不通过"));

assert(1==2,  new Exception("验证不通过"));
// assert.exception = 1 时,Fatal error: Uncaught Exception: 验证不通过
// assert.exception = 0 时,Warning: assert(): Exception: 验证不通过

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.

try{
    assert(1==2,  new Exception("验证不通过"));
}catch(Exception $e){
    echo "验证失败!:", $e->getMessage(), PHP_EOL;
}
// 验证失败!:验证不通过

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_ACTIVE | assert.active | 1 | Enable assert() assertion ASSERT_WARNING | assert.warning | 1 | Generate a PHP warning for each failed assertion ASSERT_BAIL | assert.bail | 0 | Abort execution on assertion failure ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | Disable error_reporting when assertion expressions are evaluated ASSERT_CALLBACK | assert.callback | (NULL) | Call the callback function when the assertion fails

The meaning of these parameters is very easy to understand, you can test it yourself. Let’s take a look at the function of the last ASSERT_CALLBACK. In fact, its description is also very clear, that is, if the assertion fails, it will enter the callback function defined by this option.

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====

When the assertion fails, we enter the callback function, and the callback function simply prints the content of the parameters passed to the callback function. It can be seen that the file information passed in this callback function cannot pass the assertion.

Summary

Learning to master the use and configuration of assertion functions can lay the foundation for us to learn PHPUnit unit testing in the future. Of course, there are not many things with this ability. , just remember it everyone!

测试代码:
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

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of A brief discussion on the usage of assertion functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor