assert

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

assertConfere se uma afirmação é false

Descrição

PHP 5 e 7

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

PHP 7

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

assert() verifica a assertion informada e toma a ação apropriada se seu resultado é false.

Asserts tradicionais (PHP 5 e 7)

Se o parâmetro assertion é dado como uma string ela será avaliada como código PHP pela função assert(). As vantagens de uma assertion string são menor sobrecarga na conferência se a afirmação é verdadeira e mensagens contendo assertion quando a afirmação é falsa. Isto indica que se você passar uma condição booleana (verdadeiro ou falso) como assertion esta condição não será mostrada como parâmetro da função de assert, o qual você deve ter definido com a função assert_options(), a condição é convertida para uma string antes que a função gerenciadora seja chamada e o booleano false é convertido para uma string vazia.

Asserts devem ser usadas apenas com a intenção de eliminar erros apenas. Você deve usa-las para testar condições que devam ser sempre true e que indiquem algum erro de programação ou para verificar a existência/disponibilidade de funções, extensões ou ainda de limites e recursos do sistema.

Asserts não devem ser usadas para operações em tempo de execução normais como para conferir certo valor de entrada. Como uma dica de uso, o seu código deve funcionar corretamente mesmo que os asserts não estejam ativados.

O funcionamento de assert() pode ser configurado por assert_options() ou pelas configurações descritas na pagina do manual para estas funções.

A função assert_options() e/ou a diretiva de configuração ASSERT_CALLBACK permitem configurar uma função para ser chamada no caso de falha da afirmação.

assert() callbacjs são particularmente úteis quando estiver criando sistemas automáticos para testes porque permitem que você capture facilmente o código passado para a afirmação em conjunto com informações sobre onde a afirmação foi feita. Enquanto esta informação pode ser capturada por outros métodos, usar afirmações torna muito mais fácil e rápido!

A função de callback deve aceitar três argumentos. O primeiro irá conter o arquivo onde houve a falha na afirmação. O segundo argumento irá conter a linha onde a afirmação falhou e o terceiro argumento irá conter a expressão que falhou (se houver alguma — valores literais como 1 or "dois" não serão passados nesse argumento). Usuários do PHP 5.4.8 e posteriores também devem providenciar um quarto argumento opcional, que conterá o description informado no assert() it was set.

Expectativas (somente PHP 7)

assert() é um constructo de linguagem no PHP 7, permitindo a definição de expectativas: asserts que tem efeitos em ambientes de desenvolvimento e testes, mas que são removidos com custo zero em produção.

Ainda que assert_options() possa ser utilizado para controlar comportamentos descritos acima por razões de compatibilidade reversa, o PHP 7 somente deve usar duas novas diretivas para controlar o comportamento de assert() e evitar chamar assert_options().

Diretivas de configuração para assert() no PHP 7
Diretiva Padrão Valores possíveis
zend.assertions 1
  • 1: gera e executa código (modo de desenvolvimento)
  • 0: gera código, mas não o executa
  • -1: não gera código (modo de produção)
assert.exception 0
  • 1: interrompe se o assert falhar, ou lançando a exceção fornecida no parâmetro exception ou lançando um objeto AssertionError se exception não tiver sido informado
  • 0: usa e gera um Throwable como descrito acima, mas somente gera um warning em baseado no objeto em vez de lançar a exceção (comportamento compatível com o PHP 5)

Parâmetros

assertion

A asserção. No PHP 5 isto precisa ser uma string a ser executada ou um boolean para ser testado. No PHP 7 pode ser também uma expressão que retorna valores, qual será executada e o resultado será usado para indicar se a asserção confirmou-se ou falhou.

description

Uma descrição opctional que será incluída na mensagem de falha de caso de assertion falhar.

exception

No PHP 7 o segundo parâmetro pode ser um objeto Throwable em vez de uma string string, e nesse caso o objeto será lançado caso o assert falhe e assert.exception estiver habilitado.

Valor Retornado

false se o assert é falso, true nos demais casos.

Changelog

Versão Descrição
7.0.0 assert() agora é um constructo de linguagem e não mais uma função. assertion() agora pode ser uma expressão. O segundo parâmtro pode ser interpretado como um exception (se do tipo Throwable) ou como uma string, funcionando como o campo description do PHP 5.4.8 e posteriores.
5.4.8 O parâmetro description foi adicionado. O parâmetro description é informado na função callback no modo ASSERT_CALLBACK como o quarto argumento.

Exemplos

Asserts tradicionais (PHP 5 e 7)

Exemplo #1 Lida com um assert falho com um manipulador próprio

<?php
// Ativa asserts configura silêncio
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// Cria a função de manipulação
function my_assert_handler($file$line$code)
{
    echo 
"<hr>Assertion Failed:
        File '
$file'<br />
        Line '
$line'<br />
        Code '
$code'<br /><hr />";
}

// Configura o callback
assert_options(ASSERT_CALLBACK'my_assert_handler');

// Realiza um assert que deve falhar
assert('mysql_query("")');
?>

Exemplo #2 Utilizando um manipulador para imprimir uma descrição

<?php
// Ativa asserts configura silêncio
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// Cria a função de manipulação
function my_assert_handler($file$line$code$desc null)
{
    echo 
"Assertion failed at $file:$line$code";
    if (
$desc) {
        echo 
": $desc";
    }
    echo 
"\n";
}

// Configura o 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');
?>

O exemplo acima irá imprimir:

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

Expectativas (somente PHP 7)

Exemplo #3 Expectativs sem uma exceção configurada

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

Com zend.assertions configurado para 0 o exemplo acima imprimirá:

Hi!

Com zend.assertions configurado para 1 e assert.exception para 0 O exemplo acima imprimirá:

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

Com zend.assertions configurado para 1 e assert.exception para 1 o exemplo acima imprimirá:

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

Exemplo #4 Expectativs com uma exceção configurada

<?php
class CustomError extends AssertionError {}

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

Com zend.assertions configurado para 0 o exemplo acima imprirá:

Hi!

Com zend.assertions configurado para 0 e assert.exception para 0 o exemplo acima imprimirá:

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

Com zend.assertions configurado para 1 e assert.exception para 1 o exemplo acima imprimirá:

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

Veja Também

add a note add a note

User Contributed Notes 8 notes

up
18
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
2
Krzysztof &#39;ChanibaL&#39; Bociurko
16 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
0
Tom
4 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
-3
jason at jaypha dot com
6 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
-6
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