HOWTO · PHP

PHP 检查函数是否存在

本教程演示了如何在 PHP 中检查函数是否存在。

PHP 有一个名为 function_exists() 的内置函数来检查一个函数是否存在,它可以检查任何内置或定义的函数。本教程演示了如何在 PHP 中使用 function_exists()

使用 function_exists() 检查 PHP 中内置函数的可用性

function_exists() 的返回值是布尔值。让我们检查来自不同库的函数。

例子:

<?php
//Check a function from cURL library
if (function_exists('curl_close'))
{
    echo "The function curl_close is available.<br>";
}
else
{
    echo "The function curl_close is not available.<br>";
}
//Check a function from gettext library
if (function_exists('gettext()'))
{
    echo "The function gettext() is available.<br>";
}
else
{
    echo "The function gettext() is not available.<br>";
}
//Check a function from ftp library
if (function_exists('ftp_alloc'))
{
    echo "The function ftp_alloc() is available.<br>";
}
else
{
    echo "The function ftp_alloc() is not available.<br>";
}
//Check a function from GD library
if (function_exists('imagecreatefromgif'))
{
    echo "The function imagecreatefromgif is available.<br>";
}
else
{
    echo "The function imagecreatefromgif is not available.<br>";
}
?>

代码检查来自 cURLgettextftpgd 库的函数。其中两个库被启用,另外两个被禁用。

输出:

The function curl_close is available.
The function gettext() is not available.
The function ftp_alloc() is not available.
The function imagecreatefromgif is available.

使用 function_exists() 检查 PHP 中的用户定义函数

function_exists() 可以在检查之前或之后检查定义的函数。

例子:

<?php
function demofunction()
    {
       //Anything
}

if (function_exists('demofunction')) {

    echo "demofunction exists<br>";
}
else{

    echo "demofunction doesn't exists.<br>";
}

if (function_exists('demofunction1')) {

    echo "demofunction1 exists<br>";
}
else{

    echo "demofunction1 doesn't exists.<br>";
}
function demofunction1()
    {
       //Anything
}
?>

上面的代码检查两个函数。一个在检查之前定义,一个在检查之后定义。

输出:

demofunction exists
demofunction1 exists

在 PHP 中检查环境中存在的所有函数

PHP 还有一个内置函数来检查环境中的所有函数。

例子:

<?php
var_dump( get_defined_functions());
 ?>

输出将获得环境中存在的所有功能。输出是一个非常大的数组,因此我们将其最小化为几个成员。

输出:

array(2) { ["internal"]=> array(1224) { [0]=> string(12) "zend_version" [1]=> string(13) "func_num_args" [2]=> string(12) "func_get_arg" [3]=> string(13) "func_get_args" [4]=> string(6) "strlen" [5]=> string(6)...