function_exists()

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 
我是自定义函数