简体   繁体   English

如何在PHP中使用常量?

[英]How to use constants in PHP?

I would like to use constants in PHP but "WEB" gets interpreted as false . 我想在PHP中使用常量,但是"WEB"被解释为false I never used constants before, what do I miss? 我以前从未使用过常量,我会错过什么?

define("WEB", true);
define("MOBILE", false);
define("DESKTOP", false);


if (defined('MOBILE' == true) || defined('DESKTOP' == true) ){
echo "MOBILE or DESKTOP";
} else if (defined('WEB' == true)) {
echo "WEB";
}

You are using defined() incorrectly. 您使用的defined()错误。 You are not checking if the constants are defined. 您不检查常量是否已定义。 You are checking their values. 您正在检查其值。 Just check them like you would a variable: 就像检查变量一样检查它们:

if (MOBILE == true || DESKTOP == true ){
echo "MOBILE or DESKTOP";
} else if (WEB == true) {
echo "WEB";
}

Which can be shortened to: 可以缩短为:

if (MOBILE || DESKTOP){
echo "MOBILE or DESKTOP";
} else if (WEB) {
echo "WEB";
}

defined gives you whether or not the constant exists, not its value. defined了常量是否存在,而不是常量的值。

if (MOBILE || DESKTOP){
  echo "MOBILE or DESKTOP";
} else if (WEB) {
  echo "WEB";
}

If you want to check if constant is defined, your code should be: 如果要检查是否定义了常量,则代码应为:

define("WEB", true);
define("MOBILE", false);
define("DESKTOP", false);

if(defined('MOBILE') || defined('DESKTOP'))
  echo "either MOBILE or DESKTOP is defined";
elseif(defined('WEB')) echo "WEB is defined";

If you want to check if constant value is true or false it would be 如果您要检查常数值是true还是false,那就是

if(MOBILE || DESKTOP)
  echo "either MOBILE or DESKTOP is true";
elseif(WEB) echo "WEB is true";

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

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