2012-07-28 70 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