PHP常量已定义


PHP const defined

为什么下面的代码给我一个异常,说我的常数没有定义

MyClass::myFunction(MyClass::MY_CONST); // THIS GIVES THE ERROR   
// This is the class..
class MyClass {
    const MY_CONST = 'BLA';
    public static function myFunction($key) {
        if (!defined($key)) {
            throw new Exception("$key is not defined as a constant");
        }
    }
}

我试过

  • if (!defined($key)) {}
  • if (!defined(self::$key)) {}
  • if (!defined(__CLASS__ . $key)) {}

您必须将其作为字符串传递:

public static function myFunction($key) {
    if (!defined('self::'.$key)) {
        throw new Exception("$key is not defined as a constant");
    }
}

MyClass::myFunction('MY_CONST');

正如Daniele D所指出的,对于starts,您使用常量的值而不是其名称来调用它。

在检查类常量时,defined需要不同的参数语法,而不是已定义的常量。应该是

if (!defined('self::' . $key)) {

您需要将整个类名和常量作为字符串传递。

类似:

MyClass::myFunction('MyClass::MY_CONST');