PHP Doku:: Prüft ab, ob eine Bedingung oder Abfrage FALSE ist - function.assert.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDas Verhalten von PHP beeinflussenPHP-Optionen und -InformationenPHP-Optionen-/-Informationen-Funktionenassert

Ein Service von Reinhard Neidl - Webprogrammierung.





(PHP 4, PHP 5)

assert Prüft ab, ob eine Bedingung oder Abfrage FALSE ist


int assert ( string|bool $assertion )

assert() überprüft den übergebenen Parameter assertion und führt ein über die Funktion assert_options() definiertes Ereignis aus, falls die in assertion spezifizierte Bedingung FALSE ist.

Wird der Parameter assertion als String übergeben, so wird der String als PHP-Code interpretiert. Der Vorteil der Übergabe des Parameters assertion als Zeichenkette liegt darin, dass die ausgegebene Meldung die über assertion übergebene Zeichenkette enthält.

assert() sollte nur zum Debuggen des Codes und nicht in Produktionsumgebungen verwendet werden werden, beispielsweise zur Überprüfung von Eingaben.

Die Optionen für die assert() können über die Funktion assert_options() oder in den Einstellungen der .ini-Datei gesetzt werden.

Die Funktion assert_options() mit der ASSERT_CALLBACK Direktive ermöglicht eine Funktion anzugeben, die bei fehlender Überprüfung aufgerufen wird.

Callback-Funktionen in Zusammenhang mit assert() sind nützlich, um beispielsweise automatisierte Tests durchzuführen, da die Callback-Funktion über die Information verfügt, von welcher Stelle sie aufgerufen wurde.

Die Callback-Funktion wird mit drei Parametern aufgerufen. Der erste Parameter enthält den Namen des Scripts, in dem die Überprüfung statt fand, der zweite Parameter die Zeilennummer, und der dritte Paramter enthält die über assertion angegebene Bedingung.

Beispiel #1 Überprüfung mit benutzerdefinierter Funktion

// Active assert and make it quiet
assert_options (ASSERT_ACTIVE1);
assert_options (ASSERT_WARNING0);
assert_options (ASSERT_QUIET_EVAL1);

// Create a handler function
function my_assert_handler ($file$line$code) {
"<hr>Assertion Failed:
        File '
        Line '
        Code '

// Set up the callback
assert_options (ASSERT_CALLBACK'my_assert_handler');

// Make an assertion that should fail
assert ('mysql_query ("")');

6 BenutzerBeiträge:
- Beiträge aktualisieren...
uramihsayibok, gmail, com
20.06.2010 22:48
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.


('is_int($int) /* $int parameter must be an int, not just numeric */');

// and my personal favorite
assert('false /* not yet implemented */');


The comment will show up in the output (or in your assertion handler) and doesn't require someone debugging to go through your code trying to figure out why the assertion happened. That's no excuse to not comment your code, of course.

You need to use a block comment (/*...*/) because a line comment (//...) creates an "unexpected $end" parse error in the evaluated code. Bug? Could be.
(You can get around it with "false // not yet implemented\n" but that screws up the message)
hodgman at ali dot com dot au
29.07.2008 6:19
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.
Krzysztof 'ChanibaL' Bociurko
2.10.2007 3:13
Note that func_get_args() should be used carefully and never in a string! For example:

function asserted_normal($a, $b) {
asserted_string($a, $b) {

<?php asserted_normal(1,2) ?> prints
array(2) {

but <?php asserted_string(3,4) ?> prints
array(1) {
  string(25) "var_dump(func_get_args())"

This is because of that the string passed to assert() is being evaled inside assert, and not your function. Also, note that this works correctly, because of the eval scope:

function asserted_evaled_string($a, $b) {
array(2) {

(oh, and for simplicity's sake the evaled code doesn't return true, so  don't worry that it fails assertion...)
13.09.2006 19:51
Here is a simple demonstration of Design By Contract with PHP


assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 1);
assert_options(ASSERT_CALLBACK, 'dcb_callback');

dcb_callback($script, $line, $message) {
"<h1>Condition failed!</h1><br />
        Script: <strong>
$script</strong><br />
        Line: <strong>
$line</strong><br />
        Condition: <br /><pre>

// Parameters
$a = 5;
$b = 'Simple DCB with PHP';

// Pre-Condition
    is_integer($a) &&
    ($a > 0) &&
    ($a < 20) &&
    is_string($b) &&
    (strlen($b) > 5);

// Function
function combine($a, $b) {
"Kombined: " . $b . $a;

$result = combine($a, $b);

// Post-Condition
    is_string($result) &&
    (strlen($result) > 0);

// All right, the Function works fine

gk at proliberty dot com
27.08.2005 4:35
If you expect your code to be able to work well with other code, then you should not make any assumptions about the current state of assert_options() flags, prior to calling assert(): other code may disable ASSERT_ACTIVE, without you knowing it - this would render assert() useless!

To avoid this, ALWAYS set assert_options() IMMEDIATELY before calling assert(), per the C++ paradigm for assertion usage:

In one C++ source file, you can define and undefine NDEBUG multiple times, each time followed by #include <cassert>, to enable or disable the assert macro multiple times in the same source file.

Here is how I workaround this issue in my PHP code:

/// phpxAssertHandler_f
 * @desc     Handler which also sets up assert options if not being called as handler
                 Always fatal when assertion fails
                 Always make sure assertion is enabled
                 Cannot depend on other code not using assert or using its own assert handler!
            // customize error level of assertion (php assert_options() only allows E_WARNING or nothing at all):
            // control assertion active state: not dependent on anything another piece of code might do with ASSERT_ACTIVE
            // use alternate assertion callback function:
            // NOTE: pass null as custom options parameter to use default options
            // NOTE: pass no values for assert options parameter array elements to use default options
 * @param   mixed = file or options
 * @param   line
 * @param   code
 * @return   void
function phpxAssertHandler_f($file_or_custom_options=null, $line_or_assert_options=null, $code=null){

$debug = false;

    if (
// set default assert_options
$assert_options[]=0;//ASSERT_WARNING -

        // set default custom_options
$custom_options[]=E_USER_ERROR;// error level           

if (!is_null($line_or_assert_options)){
// assert_options are passed in
if (!is_array($line_or_assert_options)){
            foreach (
$line_or_assert_options as $i=>$assert_option){
                if (
$assert_option===true) $assert_option=1;
                if (
$assert_option===false) $assert_option=0;
$debug) echo ("assert_options[$i]=$assert_option\n");

        if (!
// custom_options are passed in
if (!is_array($file_or_custom_options)){
            foreach (
$file_or_custom_options as $i=>$custom_option){
                if (
$custom_option===true) $custom_option=1;
                if (
$custom_option===false) $custom_option=0;
$debug) echo ("custom_options[$i]=$custom_option\n");

// set assert options
@assert_options (ASSERT_ACTIVE, $assert_options[0]);
assert_options (ASSERT_WARNING, $assert_options[1]);
assert_options (ASSERT_QUIET_EVAL, $assert_options[2]);
assert_options (ASSERT_CALLBACK, $assert_options[3]);        

    } else {
// we are acting as a callback function
$file = $file_or_custom_options;
$line = $line_or_assert_options;
$msg="ASSERTION FAILED: $code";
phpxErrorHandler_f ($custom_options[0],$msg,$file,$line);
nyk at forumone dot com
27.08.2002 3:56
Assertion is a useful debugging feature, but for building unit tests and automated regression tests you should seriously consider using the PHPtest in the PEAR archive ( that is based on the JUnit framework for Java. There is also another unit testing framework, also based on JUnit and also called PHPunit on SourceForge ( I believe it is an independent effort from that on PEAR.

PHP Powered Diese Seite bei
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)