2012-07-28 67 views
1
const 

    STUFF  = 1, 
    MORE_STUFF = 3, 
    ... 
    LAST_STUFF = 45; 


function($id = self::STUFF){ 
    if(defined('self::'.$id)){ 
    // here how do I get the name of the constant? 
    // eg "STUFF" 
    } 
} 

我可以得到它沒有一個巨大的病例陳述?如何獲取常量的名稱?

+0

你必須詳細說明;目前它沒有多大意義。你打算如何獲得這個名字?從'$ id'的值?並且*爲什麼*你需要常量的名字?你打算用這個名字做什麼? – knittl 2012-07-28 09:48:19

+0

函數簽名意味着您需要傳遞常量的值,但函數體只有在傳遞常量的*名稱*時才能正常工作。當你不帶任何參數地調用這個函數時,你基本上會問「是否定義了self :: 1」?這肯定不是你想要的。 – DCoder 2012-07-28 09:48:25

+0

是的,這是一個不好的嘗試,以獲得恆定:(無論如何,我仍然想得到的名稱..(並檢查是否定義) – Alex 2012-07-28 09:49:36

回答

3

看一看ReflectionClass::getConstants

喜歡的東西(這是很醜陋和低效,順便說一句):

class Foo { 
    const 

     STUFF  = 1, 
     MORE_STUFF = 3, 
     ... 
     LAST_STUFF = 45;  

    function get_name($id = self::STUFF) 
    { 
     $rc = new ReflectionClass ('Foo'); 
     $consts = $oClass->getConstants(); 

     foreach ($consts as $name => $value) { 
      if ($value === $id) { 
       return $name; 
      } 
     } 
     return NULL; 
    } 
} 
2

可以使用[Reflection][1]這一點。

假設你有下面的課。

class Profile { 
    const LABEL_FIRST_NAME = "First Name"; 
    const LABEL_LAST_NAME = "Last Name"; 
    const LABEL_COMPANY_NAME = "Company"; 
} 


$refl = new ReflectionClass('Profile'); 
print_r($refl->getConstants()); 
1

PHP:

  1. 使用從你的類名ReflectionClass
  2. 使用getConstants()方法
  3. 現在你可以scaning getConstants()結果和驗證用於獲取目標名稱
  4. 結果值

========================================

C#

你的答案就在這裏通過喬恩斯基特

Determine the name of a constant based on the value

或者使用enume(enume名稱轉換爲字符串容易:)

public enum Ram{a,b,c} 
Ram MyEnume = Ram.a; 
MyEnume.ToString() 
+0

你給的鏈接是指向一個關於C#語言的問題,而不是PHP語言。你的回答看起來不像是有效的PHP代碼。 – Jocelyn 2012-07-28 10:06:45

+0

是的,我添加了php方法 – RAM 2012-07-28 10:09:32