Home  >  Article  >  php教程  >  php判断变量常量是否存在

php判断变量常量是否存在

WBOY
WBOYOriginal
2016-06-13 10:16:12968browse

在php中变量类型我们有常用变量与常量,下面我来给大家介绍如何在php中来判断常量与变量是否己经在存了,有需要了解的朋友可进入参考。

defined() 函数检查某常量是否存在。

若常量存在,则返回 true,否则返回 false。

 代码如下 复制代码


if (defined('MYCONSTANT')) {   
    echo "常量MYCONSTANT存在";
}else{
    echo "常量MYCONSTANT不存在";
}
echo "
";


isset函数是检测变量是否设置。

1.若变量不存在则返回 FALSE
2.若变量存在且其值为NULL,也返回 FALSE
3.若变量存在且值不为NULL,则返回 TURE
4.同时检查多个变量时,每个单项都符合上一条要求时才返回 TRUE,否则结果为

 代码如下 复制代码

$var = '';

if (isset($var)) {
print "This var is set set so I will print.";
}

// 在后边的例子中,我们将使用 var_dump函数 输出 isset() 的返回值。

$a = "test";
$b = "anothertest";

var_dump( isset($a) ); // TRUE
var_dump( isset ($a, $b) ); // TRUE

unset ($a);

var_dump( isset ($a) ); // FALSE
var_dump( isset ($a, $b) ); // FALSE

$foo = NULL;
var_dump( isset ($foo) ); // FALSE

?>

这对于数组中的元素也同样有效:

 代码如下 复制代码

$a = array ('test' => 1, 'hello' => NULL);

var_dump( isset ($a['test') ); // TRUE
var_dump( isset ($a['foo') ); // FALSE
var_dump( isset ($a['hello') ); // FALSE

// 'hello' 等于 NULL,所以被认为是未赋值的。
// 如果想检测 NULL 键值,可以试试下边的方法。
var_dump( array_key_exists('hello', $a) ); // TRUE

?>

 

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

Statement:
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