assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assertVerifica se un'asserzione è false

Descrizione

PHP 5

assert(mixed $assertion, string $description = ?): bool

PHP 7

assert(mixed $assertion, Throwable $exception = ?): bool

assert() verifica l' assertion data e prende gli opportuni provvedimenti se il suo risultato è false.

Asserzioni tradizionali (PHP 5 e 7)

Se il parametro assertion è una stringa, verrà valutata come codice PHP da assert(). I vantaggi di usare le stringhe con assertion sono meno overhead nella verifica e la visualizzazione dei messaggi che contengono assertion quando questa fallisce. Ciò significa che se si passa una condizione booleana come assertion, questa condizione non sarà mostrata come parametro della funzione di asserzione che può essere definita con la funzione assert_options(), la condizione è convertita in una stringa prima di chiamare la funzione handler, e il valore booleano false viene convertito in una stringa vuota.

Le asserzioni dovrebbero essere utilizzate solo per il debug. Si possono usare per controlli di coerenza che testano per condizioni che dovrebbero essere sempre true e che, in caso contrario, indichino errori di programmazione, oppure per verificare la presenza o meno di certe caratteristiche, tipo le estensioni, oppure certi limiti di sistema o caratteristiche.

Le asserzioni non dovrebbero essere utilizzate per le normali operazioni di runtime quali il controllo dei parametri di input. Come regola si deve avere che il programma debba funzionare correttamente anche disabilitando le regole di asserzione.

Il comportamento di assert() può essere impostato tramite assert_options() oppure tramite .ini-settings come descritto nelle pagine del manuale relative a quelle funzioni.

La funzione assert_options() e/o il parametro ASSERT_CALLBACK permettono/e di attivare una funzione di callback per gestire una asserzione fallita.

Le callback di assert() sono particolarmente utili per costruire suite di test poiché permettono di catturare facilmente il codice passato all'assert, oltre alle informazioni su dove l'assert è scattato. Sebbene quest'ultime informazioni siano rilevabili anche con altri metodi, l'uso delle asserzione rende il tutto molto più veloce e semplice!

Le funzioni di callback devono accettare tre parametri. Il primo conterrà il nome del file in cui si trova l'asserzione fallita. Il secondo parametro conterrà il numero di linea dell'asserzione fallita, ed il terzo parametro conterrà l'espressione dell'asserzione fallita (se qualsiasi — valore letterale come 1 o "due" non verrà passato con questo parametro). Gli utenti di PHP 5.4.8 e successivi possono anche fornire un quarto parametro opzionale, che conterrà la description data all'assert(), se è stata impostata.

Aspettative (solo PHP 7)

assert() è un costrutto del linguaggio in PHP 7, consentendo la definizione delle aspettative: asserzioni che hanno effetto in ambienti di sviluppo e di test, ma sono ottimizzate per avere un costo zero in produzione.

Mentre assert_options() può ancora essere utilizzata per controllare il comportamento come sopra descritto per ragioni di retrocompatibilità, il codice solo per PHP 7 dovrebbe usare le due nuove direttive di configurazione per controllare il comportamento di assert() e non chiamare assert_options().

Direttive di configurazione di PHP 7 per assert()
Direttiva Valore predefinito Valori possibili
zend.assertions 1
  • 1: genera ed esegue il codice (modalità di sviluppo)
  • 0: genera il codice ma lo salta in fase di runtime
  • -1: non genera il codice (modalità di produzione)
assert.exception 0
  • 1: segnala quando l'asserzione fallisce, o sollevando l'oggetto fornito come exception o sollevando un nuovo oggetto AssertionError se exception non è stato fornito
  • 0: utilizza o genera un Throwable come descritto sopra, ma genera solo un warning basato su quell'oggetto al posto di sollevarlo (compatibile con il comportamento di PHP 5)

Elenco dei parametri

assertion

L'asserzione. In PHP 5, questo deve essere o una string da essere valutata o un boolean da testare. In PHP 7, questo può anche essere qualsiasi espressione che restituisce un valore, che verrà eseguita e il risultato usato per indicare se l'asserzione è riuscita o meno.

description

Una descrizione opzionale che sarà inclusa nel messaggio di fallimento se l'assertion fallisce.

exception

In PHP 7, il secondo parametro può essere un oggetto Throwable al posto di una string descrittiva, nel qual caso questo è l'oggetto che sarà sollevato se l'asserzione fallisce e la direttiva di configurazione assert.exception è abilitata.

Valori restituiti

false se l'asserzione è false, true in caso contrario.

Log delle modifiche

Versione Descrizione
7.0.0 assert() è ora un costrutto del linguaggio e non una funzione. assertion() ora può essere usata come un'espressione. Il secondo parametro è ora interpretato o come un exception (se viene passato un oggettoThrowable), o come la description supportato da PHP 5.4.8 in poi.
5.4.8 È stato aggiunto il parametro description. La description è anche ora fornita ad una funzione di callback in modalità ASSERT_CALLBACK come quarto parametro.

Esempi

Asserzioni tradizionali (PHP 5 e 7)

Example #1 Gestione di un'asserzione fallita con un handler personalizzato

<?php
// Attiva l'asserzione e la rende silenziosa
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Crea una funzione handler
function my_assert_handler($file, $line, $code)
{
echo
"<hr>Assertion Failed:
File '
$file'<br />
Line '
$line'<br />
Code '
$code'<br /><hr />";
}

// Imposta la callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Fa un'asserzione che dovrebbe fallire
assert('mysql_query("")');
?>

Example #2 Uso di un gestore personalizzato per stampare una descrizione

<?php
// Attiva l'asserzione e la rende silenziosa
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Crea una funzione handler
function my_assert_handler($file, $line, $code, $desc = null)
{
echo
"Assertion failed at $file:$line: $code";
if (
$desc) {
echo
": $desc";
}
echo
"\n";
}

// Imposta la callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Fa un'asserzione che dovrebbe fallire
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

Il precedente esempio visualizzerà:

 Assertion failed at test.php:21: 2 < 1
 Assertion failed at test.php:22: 2 < 1: Two is less than one
 

Aspettative (solo PHP 7)

Example #3 Aspettative senza un'eccezione personalizzata

<?php
assert
(true == false);
echo
'Hi!';
?>

Con zend.assertions impostato a 0, l'esempio di sopra stamperà:

Hi!

Con zend.assertions impostato a 1 e assert.exception impostato a 0, l'esempio di sopra stamperà:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

Con zend.assertions impostato a 1 e assert.exception impostato a 1, l'esempio di sopra stamperà:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Example #4 Aspettative con un'eccezione personalizzata

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo
'Hi!';
?>

Con zend.assertions impostato a 0, l'esempio di sopra stamperà:

Hi!

Con zend.assertions impostato a 1 e assert.exception impostato a 0, l'esempio di sopra stamperà:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

Con zend.assertions impostato a 1 e assert.exception impostato a 1, l'esempio di sopra stamperà:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

Vedere anche:

add a note add a note

User Contributed Notes 8 notes

up
19
hodgman at ali dot com dot au
15 years ago
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.
up
5
mail<at>aaron-mueller.de
17 years ago
Here is a simple demonstration of Design By Contract with PHP

<?php

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

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

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

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

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

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

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

// All right, the Function works fine
var_dump($result);

?>
up
1
Tom
3 years ago
When migrating older code to PHP 7.2+, you may get E_DEPRECATED warnings for every call to assert() you ever wrote, urging you to not pass the assertion as a string.

It may be tempting to just run a regular expression across your files to convert all strings within "assert(...)" to statements. But, before you do that, be aware of the following caveat!

For example, this code simply asserts that $input is not empty.

assert('$input;');

This works, because the string passed to assert() is evaluated as a PHP statement and the result cast to Boolean.

If you want to have an equivalent statement that doesn't pass the first parameter as a string, your regular expression should rewrite this statement as:

assert((bool) ($input));

However, this looks a bit bulky and it is tempting to instead opt for the more direct approach to convert the above line to this:

assert($input);

But! This new statement will do one of three things:

1) Looks as if it worked as intended because $input just happens to be Boolean to begin with
2) Throw a parse error if $input is a string (best case)
3) Allow an attacker on a poorly configured server to execute arbitrary PHP-Code (worst case)

The reason is that, even though on PHP 7.2+ a E_DEPRECATED warning is raised, if assert() finds the first parameter to be a string, it will still execute it as PHP-Code, just as if it was called with a string to begin with.

If an attacker finds a way to manipulate the contents of $input, you might end up with a remote code execution vulnerability. So just be extra careful when migrating assertions.
up
2
Krzysztof &#39;ChanibaL&#39; Bociurko
15 years ago
Note that func_get_args() should be used carefully and never in a string! For example:

<?php
function asserted_normal($a, $b) {
   
assert(var_dump(func_get_args()));
    }
function
asserted_string($a, $b) {
   
assert('var_dump(func_get_args())');
    }
?>

<?php asserted_normal(1,2) ?> prints
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

but <?php asserted_string(3,4) ?> prints
array(1) {
  [0]=>
  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:

<?php
function asserted_evaled_string($a, $b) {
   
assert(eval('var_dump(func_get_args())'));
    }
asserted_evaled_string(5,6);
?>
array(2) {
  [0]=>
  int(5)
  [1]=>
  int(6)
}

(oh, and for simplicity's sake the evaled code doesn't return true, so  don't worry that it fails assertion...)
up
-4
jason at jaypha dot com
5 years ago
You can take advantage of how assert is handled to use it for crude conditional compilation.

For example

<?php
  assert
(print("Some debug message\n"));
 
assert(($val = "dev") || true);
?>

Since print() always returns 1, the topmost assertion will pass. For others, you may need to add a || true. Always enclose the expression in ().

In a development environment where zend.assertions=1, the above code will execute. In production environments where zend.assertions=-1, it wont even compile, thus not burdening performance.

Another, more real world, example.

<?php
  $cssSrc
= 'https://code.jquery.com/jquery-3.2.1.min.js';
 
assert(($cssSrc = 'http://dev.local/jquery-3.2.1.js') || true);
  echo
"<link rel='stylesheet' type='text/css' href='$cssSrc'/>\n";
?>

In a production environment, The website will use the minified version from the CDN. In a development environment, a development version, sourced locally, will be used instead.

Note: This will not work for everything. Only code that can be embedded in an expression will work.
up
-7
uramihsayibok, gmail, com
13 years ago
There's a nice advantage to giving assert() some code to execute, as a string, rather than a simple true/false value: commenting.

<?php

assert
('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)
up
-2
Ben
7 years ago
if there was no 'warning' message when assertion failed (FALSE), try reset the error handler:
<?php
set_error_handler
( null );
up
-9
office dot stojmenovic at gmail dot com
10 years ago
Example from Ikac Framework how they use assert()

<?php

   
/**
     * Set Assertion Debug
     *
     * This method will check the given assertion and take appropriate -
     * action if its result is FALSE.
     *
     * This file is part of Ikac Framework.
     *
     * @package Ikac Framework
     * @author Ivan Stojmenovic Ikac <contact.@stojmenovic.info>
     *
     * @param mixed $assertion  The assertion.
     * @param mixed $callback Callback to call on failed assertions
     * @param array $options  Set the various control options or just query their current settings.
     * @param string $description  An optional description that will be included in the failure message if the assertion fails.
     */
   
public function setAssertionDebug($assertion, $callback, array $options, $description = null)
    {
        if (
is_array($options)) {
            foreach (
$options AS $option => $value) {
               
assert_options($option, $value);
            }
        }
        if (
$callback) {
           
assert_options(ASSERT_CALLBACK, $callback);
        }
       
        return
assert($assertion, $description);
    }
   
?>

How to use:

<?php
     
use Ikac\Component\SystemBehaviour\OptionsInfo;

     
$system = new OptionsInfo();

     
$option = array(ASSERT_ACTIVE => 1,ASSERT_WARNING => 0,ASSERT_QUIET_EVAL => 1);

    
$system->setAssertionDebug('2<1', function(){
            echo
"Assertion failed";
     },
$option);

?>
To Top