PHP AssertionError

PHPServer Side ProgrammingProgramming

Introduction

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

assert() checks if given assertion is true or false, and throws AssertionError if it is false. 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

Sr.NoParameter & Description
1assertion
string or boolean expression
2description
failure mssage
3exception (for PHP 7 only)
throwable object

Since PHP 7.0, assert() is now a language construct and not a function. assertion parameter can now be an expression and second parameter is either an exception, or description. From PHP 7.2 onwards, string description emits E_DEPRECATED message. The AssertionError thrown by assert() will be sent to catch block only if assert.exception=on is enabled in php.ini.

AssertionError Example

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

Example

 Live Demo

<?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 following result −

assert(10 == 20) failed.
raja
Published on 21-Sep-2020 15:02:36
Advertisements