php:function_exists
php中可以通过function_exists()函数检测另外一个函数是否存在,可以把函数名作为一个字符串传入function_exists,判断该还是是否存在
function highlight( $txt ) {
return "<sub>$txt</sub>";
}
function textWrap( $tag, $txt, $func="" ) {
if (function_exists( $func ) )
$txt = $func($txt);
return "<$tag>$txt</$tag>\n";
}
用法示例如下:
echo textWrap('i','function exists Demo','highlight');
//输出结果为斜体字的: function exists Demo
PHP function_exists() 函数用于检测函数是否被定义,检测的函数可以是 PHP 的内置函数,也可以是用户的自定义函数。如果被检测的函数存在则返回 TRUE ,否则返回 FALSE 。
语法:
bool function_exists( string function_name )
<?php
function funcb() {
echo 'This is a test func';
}
function if_ext() {
echo function_exists('funcb');
if (function_exists('funcb')) {
echo 'exits';
} else {
echo 'no exists';
}
}
#testfunc();
echo funcb();
echo if_ext();
echo function_exists('funcb');
?>
运行结果
This is a test func1exits1
检测系统内置函数,以下代码是常见的用于检查系统是否开启 GD 库:
<?php
if(function_exists('gd_info')){
echo 'GD库已经开启。';
} else {
echo 'GD库没有开启。';
}
?>
特殊情况
function_exists() 函数有个特殊情况,当参数不是以字符串函数名而是以 function_name() 形式传入参数时,function_exists() 将直接返回原函数值。
<?php
function testfunc(){
echo '我是自定义函数';
}
echo function_exists(testfunc());
?>
运行该例子输出:
php ./if_ex3.php
我是自定义函数
浙公网安备 33010602011771号