Home > Backend Development > PHP Tutorial > PHP assertion error

PHP assertion error

PHPz
Release: 2023-09-07 12:50:01
forward
872 people have browsed it

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
Copy after login

Parameters

Serial numberParameters and description
1assertion

String or Boolean expression

2description

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();
}
?>
Copy after login

Output

This will produce the following results -

assert(10 == 20) failed.
Copy after login

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

source:tutorialspoint.com
Statement of this Website
The 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.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template