PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

dl> <assert_options
Last updated: Fri, 14 Nov 2008

view this page in

assert

(PHP 4, PHP 5)

assertConfere se uma afirmação é FALSE

Descrição

bool assert ( mixed $assertion )

assert() se a afirmação assertion é falsa e toma a ação apropriada.

Se o parâmetro assertion é dado como uma string ela será avaliada como código PHP pela função assert(). As vantagens da string assertion são menor sobrecarga quando conferir 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á mostrado como parâmetro da função de afirmação, 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.

Afirmações devem ser usadas apenas com a intenção de eliminar erros. Você deve usa-las para testar condições que devam ser sempre TRUE e que indiquem algum erro de programação se não for ou para verificar a existência de certas coisas como a disponibilidade de funções de algum módulo ou limites e recursos do sistema.

Afirmações 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 o teste de afirmações não esteja ativado.

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.

Funções chamadas a partir de falhas de assert() 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 utilizada para processar as afirmações devem 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 ou "dois" não serão passados por este argumento).

Parâmetros

assertion

A afirmação.

Valor Retornado

FALSE se a afirmação for falsa, TRUE se não.

Exemplos

Exemplo #1 Gerenciando uma afirmação que falhou com uma função do usuário

<?php
// Ativa as afirmações e as deixa quietas
assert_options(ASSERT_ACTIVE1);
assert_options(ASSERT_WARNING0);
assert_options(ASSERT_QUIET_EVAL1);

// Cria a função do usuário que será chamada quando a afirmação falhar
function my_assert_handler($file$line$code)
{
    echo 
"<hr>Afirmação falhou:
        Arquivo '$file'<br />
        Linha '$line'<br />
        Código '$code'<br /><hr />"
;
}

// Define a função
assert_options(ASSERT_CALLBACK'my_assert_handler');

//  Faz uma afirmação que irá falhar
assert('mysql_query ("")');
?>



dl> <assert_options
Last updated: Fri, 14 Nov 2008
 
add a note add a note User Contributed Notes
assert
hodgman at ali dot com dot au
28-Jul-2008 09: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 &#39;ChanibaL&#39; Bociurko
01-Oct-2007 06:13
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...)
mail<at>aaron-mueller.de
13-Sep-2006 10:51
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);

?>
gk at proliberty dot com
26-Aug-2005 07: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:

<?php
//////////////////////////////////////////////////////////////////////
/// 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!
            USAGE:
            // customize error level of assertion (php assert_options() only allows E_WARNING or nothing at all):
                phpxAssertHandler_f(E_USER_NOTICE);
            // control assertion active state: not dependent on anything another piece of code might do with ASSERT_ACTIVE
                $GLOBALS['MY_ASSERT_ACTIVE']=false;
                phpxAssertHandler_f(E_USER_NOTICE,$GLOBALS['MY_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
                $GLOBALS['MY_ASSERT_ACTIVE']=false;
                $GLOBALS['MY_ASSERT_CALLBACK']='myAssertCallback';
                phpxAssertHandler_f(
                    null,
                    array(
                        0=>$GLOBALS['MY_ASSERT_ACTIVE'],
                        3=>$GLOBALS['MY_ASSERT_CALLBACK'],
                    )
                );
                
 * @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){

    static
$custom_options;
   
$debug = false;

    if (
is_null($code)){
       
// set default assert_options
       
$assert_options[]=1;//ASSERT_ACTIVE
       
$assert_options[]=0;//ASSERT_WARNING -
       
$assert_options[]=0;//ASSERT_QUIET_EVAL
       
$assert_options[]=__FUNCTION__;//ASSERT_CALLBACK       

        // 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)){
               
$line_or_assert_options=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;
               
$assert_options[$i]=$assert_option;
                if(
$debug) echo ("assert_options[$i]=$assert_option\n");
            }
        }

        if (!
is_null($file_or_custom_options)){
           
// custom_options are passed in
           
if (!is_array($file_or_custom_options)){
               
$file_or_custom_options=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;
               
$custom_options[$i]=$custom_option;
                if(
$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);
    }
}
//phpxAssertHandler_f()
?>
nyk at forumone dot com
26-Aug-2002 06: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 (http://pear.php.net/package-info.php?pacid=38) 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 (http://sourceforge.net/projects/phpunit/). I believe it is an independent effort from that on PEAR.

dl> <assert_options
Last updated: Fri, 14 Nov 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites