assert
(PHP 4, PHP 5)
assert — Checks if assertion is FALSE
Description
assert() will check the given
assertion
and take appropriate action if
its result is FALSE
.
If the assertion
is given as a string it
will be evaluated as PHP code by assert().
The advantages of a string assertion
are
less overhead when assertion checking is off and messages
containing the assertion
expression when
an assertion fails. This means that if you pass a boolean condition
as assertion
this condition will not show up as
parameter to the assertion function which you may have defined with the
assert_options() function, the condition is converted
to a string before calling that handler function, and the boolean FALSE
is converted as the empty string.
Assertions should be used as a debugging feature only. You may
use them for sanity-checks that test for conditions that should
always be TRUE
and that indicate some programming errors if not
or to check for the presence of certain features like extension
functions or certain system limits and features.
Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.
The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.
The assert_options() function and/or
ASSERT_CALLBACK
configuration directive allow a
callback function to be set to handle failed assertions.
assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!
The callback function should accept three arguments. The first
argument will contain the file the assertion failed in. The
second argument will contain the line the assertion failed on and
the third argument will contain the expression that failed (if
any — literal values such as 1 or "two" will not be passed via
this argument). Users of PHP 5.4.8 and later may also provide a fourth
optional argument, which will contain the
description
given to assert(), if
it was set.
Parameters
-
assertion
-
The assertion.
-
description
-
An optional description that will be included in the failure message if the
assertion
fails.
Return Values
FALSE
if the assertion is false, TRUE
otherwise.
Changelog
Version | Description |
---|---|
5.4.8 |
The description parameter was added. The
description is also now provided to a callback
function in ASSERT_CALLBACK mode as the fourth
argument.
|
Examples
Example #1 Handle a failed assertion with a custom handler
<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Create a handler function
function my_assert_handler($file, $line, $code)
{
echo "<hr>Assertion Failed:
File '$file'<br />
Line '$line'<br />
Code '$code'<br /><hr />";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('mysql_query("")');
?>
Example #2 Using a custom handler to print a description
<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
// Create a handler function
function my_assert_handler($file, $line, $code, $desc = null)
{
echo "Assertion failed at $file:$line: $code";
if ($desc) {
echo ": $desc";
}
echo "\n";
}
// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>
The above example will output:
Assertion failed at test.php:21: 2 < 1 Assertion failed at test.php:22: 2 < 1: Two is less than one
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Изменение поведения PHP
- PHP Опции и Информация
- assert_options
- assert
- cli_get_process_title
- cli_set_process_title
- dl
- extension_loaded
- gc_collect_cycles
- gc_disable
- gc_enable
- gc_enabled
- gc_mem_caches
- get_cfg_var
- get_current_user
- get_defined_constants
- get_extension_funcs
- get_include_path
- get_included_files
- get_loaded_extensions
- get_magic_quotes_gpc
- get_magic_quotes_runtime
- get_required_files
- get_resources
- getenv
- getlastmod
- getmygid
- getmyinode
- getmypid
- getmyuid
- getopt
- getrusage
- ini_alter
- ini_get_all
- ini_get
- ini_restore
- ini_set
- magic_quotes_runtime
- main
- memory_get_peak_usage
- memory_get_usage
- php_ini_loaded_file
- php_ini_scanned_files
- php_logo_guid
- php_sapi_name
- php_uname
- phpcredits
- phpinfo
- phpversion
- putenv
- restore_include_path
- set_include_path
- set_magic_quotes_runtime
- set_time_limit
- sys_get_temp_dir
- version_compare
- zend_logo_guid
- zend_thread_id
- zend_version
Коментарии
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."
This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.
With the current changes made in PHP 8.3 (deprecating the INI settings affecting assertions) and the increasing amount of open source libraries utilizing `assert()` as an easy means to ensure obscure return cases of PHP core function calls are in fact not triggered (e.g. no NULL or FALSE has been returned, but the useful value), the comment made about assertions only being a tool used during development should be considered invalid.
In addition, static code analysis tools use the knowledge gained from `assert($x instanceof MyClass)` to know the type or types that are possible.
Assertions are actively being used in production code, they are useful, and disabling them would only gain minimal performance benefits because the asserted expression usually is very small.
Use this tool where applicable!