assert

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

assertExecuta um assert

Descrição

assert(mixed $assertion, Throwable|string|null $description = null): bool

assert() permite a definição de expectativas: asserções são verificadas em ambientes de desenvolvimento ou testes, mas que são removidas por otimização a custo zero em produção.

Asserções devem ser utilizadas como uma ferramenta apenas de debug. Um dos usos é para funcionar como validações graves, para precondições que precisam ser true e caso isso não ocorra, isto indica algum erro de programação. Outro uso é garantir a presença de certos recursos, como por exemplo funções de extensões ou certos recursos ou limites de sistema.

As asserções podem ser configurados para serem eliminados, e elas não não devem ser utilizados em operações comuns como por exemplo a validação de parâmetros. Como regra geral, o código deve se comportar igual mesmo no caso das asserções estarem desativadas.

assert() verificará se a expectativa informada no parâmetro assertion é válida. Se não, o resultado avaliado é false, ocorrerá a ação apropriada, dependendo em como assert() está configurado.

O comportamento de assert() é ditado pelas seguintes configurações INI:

Assert Opções de Configuração
Nome Padrão Descrição Registro de Alterações
zend.assertions 1
  • 1: gera e executa o código (modo de desenvolvimento)
  • 0: gera o código mas ignora durante a execução
  • -1: não gera o código (modo de produção)
 
assert.active true Se false, assert() não verifica a expectativa e retorna true imediatamente. Descontinuado desde o PHP 8.3.0.
assert.callback null Uma função definida pelo usuário a ser chamada quando a asserção falha. A assinatura deve ser:
assert_callback(
    string $file,
    int $line,
    null $assertion,
    string $description = ?
): void
Anteriormente ao PHP 8.0.0, a assinatura deveria ser:
assert_callback(
    string $file,
    int $line,
    string $assertion,
    string $description = ?
): void
Descontinuado desde o PHP 8.3.0.
assert.exception true Se true irá lançar um AssertionError no caso da expectativa não ser válida. Descontinuado desde o PHP 8.3.0.
assert.bail false Se true então a execução do script PHP será abortada caso a expectativa não seja válida. Descontinuado desde o PHP 8.3.0.
assert.warning true Se true, será emitido um E_WARNING no caso da expectativa não seja válida. Essa configuração INI é inefetiva caso assert.exception esteja ativo. Descontinuado desde o PHP 8.3.0.

Parâmetros

assertion

Pode ser qualquer expressão que retorna um valor, qual será executado e o resultado é utilizado para indicar se a asserção deve passar ou falhar.

Aviso

Anteriormente ao PHP 8.0.0, se assertion era uma string ela era interpretada como código PHP e executada via eval(). A string era passada para o argumento do callback no terceiro argumento. Este comportamento está DESCONTINUADO desde o PHP 7.2.0, e foi REMOVIDO no PHP 8.0.0.

description

Se description é uma instância de Throwable, ela será lançada somente se assertion for executada e falhar.

Nota:

A partir do 8.0.0, isto ocorria antes de chamar a função de callback potencialmente definida.

Nota:

A partir do PHP 8.0.0, o object será lançado independente da configuração de assert.exception.

Nota:

A partird do PHP 8.0.0, a configuração assert.bail não terá efeito nesse caso.

Se description é uma string esta mensagem será utilizada em uma exceção ou em um aviso. Uma descrição opcional que será incluída na mensagem de falha no caso da assertion falhar.

Se description é omitido. Uma descrição padrão, igual ao código fonte na invocação de assert() é criada em tempo de compilação.

Valor Retornado

assert() sempre retorna true se ao menos uma das seguintes condições forem verdadeiras:

  • zend.assertions=0
  • zend.assertions=-1
  • assert.exception=1
  • assert.bail=1
  • Um objeto exception foi passado em description.

Se nenhuma das condições forem verdadeiras assert() ainda pode retornar true se assertion possa ser convertido em um valor verdadeiro, ou false nos demais casos.

Registro de Alterações

Versão Descrição
8.3.0 Todas as configurações INI assert. estão desencorajadas.
8.0.0 assert() não mais avaliará argumentos strings, e por outro lado elas serão tratadas como um argumento comum. assert($a == $b) deve ser utilizado ao invés de assert('$a == $b'). A diretiva assert.quiet_eval php.ini e a constante ASSERT_QUIET_EVAL também foram removidos, dado que elas não tem mais nenhum efeito.
8.0.0 Se description é uma instância de Throwable, a exceção é lançada no caso da asserção falhar, independentemente do valor de assert.exception.
8.0.0 Se description é uma instância de Throwable, o callback não é chamado, mesmo que ele seja informado.
8.0.0 Declarar uma função chamada assert() dentro de um namespace não é mais permitido, e emite um E_COMPILE_ERROR.
7.3.0 Declarar uma função chamada assert() dentro de um namespace foi descontinuado. Uma declaração assim emite um E_DEPRECATED.
7.2.0 Uso de strings no argumento assertion foi descontinuado. Isto agora emite um aviso E_DEPRECATED quando ambos assert.active e zend.assertions estão configurados para 1.

Exemplos

Exemplo #1 Exemplo de assert()

<?php
assert
(1 > 2);
echo
'Hi!';

Se assertions estiver ativo (zend.assertions=1), o exemplo acima emitirá:

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

Se assertions estiver desativado (zend.assertions=0 ou zend.assertions=-1) o exemplo acima emitirá:

Hi!

Exemplo #2 Utilizando uma mensagem customizada

<?php
assert
(1 > 2, "Expected one to be greater than two");
echo
'Hi!';

Se assertions estiverem ativadas, o código acima emitirá:

Fatal error: Uncaught AssertionError: Expected one to be greater than two in example.php:2
Stack trace:
#0 example.php(2): assert(false, 'Expected one to...')
#1 {main}
  thrown in example.php on line 2

Se assertions estiverem desativados, o código acima emitirá:

Hi!

Exemplo #3 Utilizando uma classe exception

<?php
class ArithmeticAssertionError extends AssertionError {}

assert(1 > 2, new ArithmeticAssertionError("Expected one to be greater than two"));
echo
'Hi!';

Se assertions estiver ativo o exemplo acima emitirá:

Fatal error: Uncaught ArithmeticAssertionError: Expected one to be greater than two in example.php:4
Stack trace:
#0 {main}
  thrown in example.php on line 4

Se assertions estiver desativado, o exemplo acima emitirá:

Hi!

Veja Também

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
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
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
-4
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
-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