Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: assert - Manual
[go: Go Back, main page]

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

search for in the

dl" width="11" height="7"/> <assert_options
Last updated: Mon, 05 Feb 2007
view this page in

assert

(PHP 4, PHP 5)

assert — assertion が FALSE であるかどうかを調べる

説明

bool assert ( mixed assertion )

assert() は、指定した assertionを調べて、結果が FALSEの場合に適当な動作をします。

assertion が文字列として指定された場合、 assert()によりPHPコードとして評価されます。 文字列 assertionが優れているところは、 assertion のチェックがオフになった場合のオーバーヘッドがより少な いことであり、assertionが失敗した場合のメッセージを式 assertionに有しています。 つまり、もし論理型の条件を assertion として渡した場合、この条件が assert_options() 関数で指定したハンドラ関数への引数とはならないということです。 条件はハンドラ関数をコールする前に文字列に変換され、論理型の FALSE は空文字列に変換されます。

assertion は、デバッグ目的にのみ使用するべきです。 assertion を常にTRUEとなる条件を調べる不具合診断に使用し、TRUEでな い場合に何らかのプログラミングエラーを示したり、extension 関数ま たは特定のシステム制限や機能といった特定の機能の存在をチェックす るために使用することが可能です。

assersion は、入力パラメータのチェックのような通常の実行動作に使 用するべきではありません。一般的には、assertion のチェックが有効 でない場合に自分のコードを常に正常に動作することができる必要があり ます。

assert() の動作は、 assert_options() またはマニュアルの関数の部分 に記述された .ini の設定により設定することが可能です。

関数 assert_options() かつ/または ASSERT_CALLBACK 設定ディレクティブにより失敗したassertionを 処理するコールバック関数を設定することが可能です。

assert() のコールバックは、assertionが発生 した場所に関する情報と共にassertionに渡されたコードを容易にキャ プチャーできるため、特に自動テストセットを構築する際に便利です。 この情報は他の手法でもキャプチャー可能ですが、assertionを使用 することにより、より簡単かつ容易に行なうことが可能です!

コールバック関数は、3つの引数を受ける必要があります。最初の引数 は、assertionが失敗したファイルが含まれます。2番目の引数には、 assertionが失敗した行が含まれ、3番目の引数には失敗した式が含ま れます。(もしある場合のみ。1または"two"のようなリテラルの値はこ の引数に渡されません)

例 1723. カスタムハンドラで失敗したassertionを処理する

<?php
// assertを有効にし、出力を抑制する
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// ハンドラ関数を作成する
function my_assert_handler($file, $line, $code)
{
   echo
"<hr>Assertion Failed:
       File '$file'<br />
       Line '$line'<br />
       Code '$code'<br /><hr />"
;
}

// コールバックを設定する
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// 失敗するassertionを作成
assert('mysql_query("")');
?>



add a note add a note User Contributed Notes
assert
tom russo at gmail dot com
25-Dec-2006 08:25
hodgman at ali dot com dot au said:
"Assertions should only be enabled during testing/development, and then disabled once your code reaches a production stage."

Assertions should _not_ be turned off in production code.  Although it's common to do so, turning off assertions in production is a bad practice.

If your production code fails an assert, YOU WANT TO KNOW ABOUT IT.  Asserts are a debugging tool, but you should not stop debugging your code just because it has gone into production.

Many people claim that removing asserts gives a performance benefit.  In modern programming languages this simply isn't true.  If you were doing an assert on something that is extremely slow/expensive to compute, you might consider turning that assert off.  But in practice this really isn't how asserts are used.

There's a good discussion of this issue in the book The Pragmatic Programmer.
mail<at>aaron-mueller.de
14-Sep-2006 02: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);

?>
hodgman at ali dot com dot au
11-Aug-2006 08:45
I dont agree with gk at proliberty dot com's statements below.

If you are constantly enabling assertions before each assertion, then you are removing the functionality provided by being able to turn off assertions in the first place.

Assertions should only be enabled during testing/development, and then disabled once your code reaches a production stage.

This means you should either leave disabling/enabling assertions up to the INI file, or let the entry point of the script decide.

If you need an assertion to be there in the final copy of the code, then you are using the wrong tool. Assertions are a tool for debugging only.
gk at proliberty dot com
27-Aug-2005 11: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!
           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()
Thomas
29-Mar-2005 12:56
Another very good unit testing framework is SimpleTest, which can be found at http://www.lastcraft.com/simple_test.php

It has very good documentation, support for mock objects and tools for automating testing of entire web sites.
nyk at forumone dot com
27-Aug-2002 10: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" width="11" height="7"/> <assert_options
Last updated: Mon, 05 Feb 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites