Home > php教程 > php手册 > body text

php 判断常量、变量和函数是否存在

WBOY
Release: 2016-06-13 10:02:20
Original
950 people have browsed it

在php开发中我们经常会面要提供预定义判断变量或常量或函数是不是有了,下面我来介绍一些常用的判断常量、变量和函数是否存在应用实例。


常量检测使用defined,定义常量则是define。注意待检测的常量需要使用引号(单双均可),如:

 代码如下 复制代码

if (defined('CONST_NAME')) {
    //do something 
}

变量检测则是使用isset,注意变量未声明或声明时赋值为NULL,isset均返回FALSE,如:

 代码如下 复制代码

if (isset($var_name)) {
    //do something
}

函数检测用function_exists,注意待检测的函数名也需要使用引号,如:

if (function_exists('fun_name')) {
 fun_name();
}

先不说多了我们看一个实例

 代码如下 复制代码


/* 判断常量是否存在*/
if (defined('MYCONSTANT')) {
echo MYCONSTANT;
}
//判断变量是否存在
if (isset($myvar)) {
echo "存在变量$myvar.";
}
//判断函数是否存在
if (function_exists('imap_open')) {
echo "存在函数imag_openn";
} else {
echo "函数imag_open不存在n";
}
?>


function_exists判断函数是否存在

 代码如下 复制代码
 
if (function_exists('test_func')) {
    echo "函数test_func存在";
} else {
    echo "函数test_func不存在";
}
?>

 

filter_has_var函数

filter_has_var() 函数检查是否存在指定输入类型的变量。

若成功,则返回 true,否则返回 false。

 

 代码如下 复制代码
if(!filter_has_var(INPUT_GET, "name"))
 {
 echo("Input type does not exist");
 }
else
 {
 echo("Input type exists");
 }
?>
 

输出为. Input type exists

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!