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)...