简体   繁体   English

检查常量是否已定义但为空?

[英]Check constant is defined but empty?

<?php
    define ('foo','');
if (defined('foo')){
    if (empty(foo)){
        echo "Notice: Foo Is Defined, But Does Not Carry A Value. Please Set It";
    }
}

If have this current script, I am running a set of checks on defined constants which the user needs to define in the configuration page.. The problem is, the config gets shipped out with nothing defined: 如果有此当前脚本,我将对用户需要在配置页中定义的已定义常量进行一组检查。问题是,配置出厂时未定义任何内容:

define ('foo','');

and when running the script, I first check that the necessary constants are correctly defined and do carry a value. 在运行脚本时,我首先检查是否正确定义了必需的常量,并且确实包含一个值。

The problem is, that I can get if the value is defined, but I cannot correctly check if it's empty. 问题是,如果定义了值,我可以得到,但是我不能正确检查它是否为空。

I know with empty expects a variable passed, if i pass my defined constants into a variable, doesn't it kinda defeat the point? 我知道空值会传递一个变量,如果我将定义的常量传递给一个变量,那不是很失败吗?

<?php
 define ('Foo','');
 $Foo = Foo;
 if (empty($Foo)){
  echo "Foo Is Empty"; 
}
?>

Whereas I might aswell setup: 而我可能还要设置:

$Foo = 'Value';
$OtherConstant = 'Another';

so how can I check whether my constant is carrying a value when that is defined? 那么如何在定义常量时检查我的常量是否带有值?

You could simply do that: 您可以简单地做到这一点:

if (defined('foo')) {
    echo 'defined';
    if (foo) {
        echo 'not empty';
    }
    else {
        echo 'empty';
    }
}
else {
    echo 'not defined';
}

If foo is an empty string the if(foo) conditional will evaluate false. 如果foo是一个空字符串, if(foo)条件的计算结果为false。 There are subtle differences between empty() and converting to boolean. empty()和转换为boolean之间有细微的差别。 Please refer to the PHP manual for other cases. 其他情况请参考PHP手册。 Boolean conversion , empty() 布尔转换empty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM