2014-10-27 62 views
1

爲什麼下面的代碼給我一個例外,說我不斷沒有定義PHP常量定義

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)) {}嘗試
+0

這是個時機問題,可以這麼說。您在定義它之前嘗試使用該常量。 – 2014-10-27 12:23:09

+1

ü需要將它作爲字符串傳遞 – DarkBee 2014-10-27 12:23:14

+0

在嘗試編寫示例代碼時,我想知道您什麼時候會使用它?如果未定義「MY_CONST」,則無法在第一行中使用它 – kero 2014-10-27 12:23:37

回答

2

你必須把它作爲一個字符串傳遞:

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


MyClass::myFunction('MY_CONST'); 
0

正如丹尼爾·d指出的,開始你與常量,而不是它的名稱的值調用它。

定義在檢查類常量時需要使用不同的語法,而不是定義的常量。它應該是

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

您需要將整個類名稱和常量作爲字符串傳遞。

像:

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