<?php $s = 123; assert("is_int($s)"); ?>从这个例子能够看到字符串参数会被执行,这跟eval()相似。不过eval($code_str)只是执行符合php编码规范的$code_str。
若是按照默认值来,在程序的运行过程当中调用assert()来进行判断表达式,遇到false时程序也是会继续执行的,这在生产环境中这样使用是很差的,而 在开发调试环境中,倒是一种debug的不错的方式。特别是用上callback的方法,能够知道具体的出错信息。例如:php
<?php // Active assert and make it quiet assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_WARNING, 0); assert_options(ASSERT_QUIET_EVAL, 1); // Create a handler function function my_assert_handler($file, $line, $code) { echo "<hr>Assertion Failed:File '$file'<br />Line '$line'<br />Code '$code'<br /><hr />"; } // Set up the callback assert_options(ASSERT_CALLBACK, 'my_assert_handler'); // Make an assertion that should fail assert('mysql_query("")'); ?>因此,php的官方文档里头是建议将assert用来进行debug,咱们能够发现还有一个开关ASSERT_ACTIVE能够用来控制是否开启debug。
个人建议是,既然assert主要做用是debug,就不要在程序发布的时候还留着它。在程序中用assert来对表达进行判断是不明智的,缘由上文说了, 一个是在生产环境中assert可能被disabled,因此assert不能被彻底信任;二是assert()能够被继续执行;而若是在生产环境让ASSERT_ACTIVE=1,那这个表达式字符串能够被执行自己就存在安全隐患。例如:mysql
<?php function fo(){ $fp = fopen("c:/test.php",'w'); fwrite($fp,"123"); fclose($fp); return true; } assert("fo()"); ?>