PHP: undefined constant while defining it

PHP: undefined constant while defining it

我在 PHP 中收到以下错误:

Notice: Use of undefined constant CONSTANT

在我定义它的那一行:

define(CONSTANT, true);

我做错了什么?我定义了,为什么会说"Undefined constant"?

你需要引用成为常量的字符串

define('CONSTANT', true);

如果你这样写,你就是在使用一个已经定义的常量的值作为常量名称。

您想做的是将名称作为字符串传递:

define('CONSTANT', true);

了解您做错了什么的最好方法是阅读 PHP 手册。

这里是 define 函数的定义。

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

所以第一个参数必须是字符串。

见下文定义常量的正确方法

define('Variable','Value',case-sensitive);

Here Variable ==> Define your Constant Variable Name
Here Value ==> Define Constant value
Here case-sensitive Defult value 'false', Also you can set value 'true' and 'false'

Although not really, strictly relevant to your case, it is most desirable to first check that a CONSTANT has not been previously defined before (re)defining it.... It is also important to keep in mind that defining CONSTANTS using define requires that the CONSTANT to be defined is a STRING ie. enclosed within Quotes like so:

<?php

    // CHECK THAT THE CONSTANTS HASN'T ALREADY BEEN DEFINED BEFORE DEFINING IT...
    // AND BE SURE THE NAME OF THE CONSTANT IS WRAPPED WITHIN QUOTES...
    defined('A_CONSTANT') or define('A_CONSTANT', 'AN ALPHA-NUMERIC VALUE', true);

    // BUT USING THE CONSTANT, YOU NEED NOT ENCLOSE IT WITHIN QUOTES.
    echo A_CONSTANT;  //<== YIELDS::   "AN ALPHA-NUMERIC VALUE"