Home  >  Article  >  Backend Development  >  PHP assertion error

PHP assertion error

PHPz
PHPzforward
2023-09-07 12:49:02846browse

PHP assertion error

Introduction

AssertionError class is a subclass of Error class. This type of error is thrown when assert() returns FALSE

assert() checks whether the given assertion is true or false, and if false, throws an AssertionError. The assert() function is defined as follows -

Syntax

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

Parameters

Serial number Parameters and description
1 assertion

String or Boolean expression

2 description

Failure message

3 exception (PHP 7 only)

Throwable object

Starting in PHP 7.0, assert() is now a language construct rather than a function. assertion The parameter can now be an expression, and the second parameter can be an exception or a description. Starting with PHP 7.2, string descriptions emit the E_DEPRECATED message. The AssertionError thrown by assert() will only be sent to the catch block if assert.exception=on is enabled in php.ini.

AssertionError Example

In this example, we assert that the condition is true and the try block executes normally. If the condition is false, an AssertionError message will be displayed from the catch block.

Example

Live Demonstration

<?php
$a=10;
$b=20;
try {
   if (assert($a == $b, "assert($a == $b) failed.")) {
      echo("assert($a == $b) was successful.");
   }
} catch (AssertionError $e) {
   echo $e->getMessage();
}
?>

Output

This will produce the following results -

assert(10 == 20) failed.

The above is the detailed content of PHP assertion error. For more information, please follow other related articles on the PHP Chinese website!

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