2017-01-03 161 views
0

我想做一个小的PHP函数,可以检查常量是否定义,如果是的话,回声它,如果没有,回声空间或什么都没有。如何检查常量是否定义,内函数 - php

现在,if(defined()部分不起作用,因为常量正在传递给函数中的一个变量。

function getConstant($constant) { 
    if(defined($constant)) { 
    echo constant($constant); 
    } else { 
    echo ''; 
    } 
} 

echo constant($constant)部分工作正常,但如果常数实际上定义,因为它是一个变量,现在我无法检查。

我似乎无法找到一个解决方案是

+1

你是什么意思的不断转移到一个变量?你的意思是常数的名字? – yivi

+1

所有工作都很好https://3v4l.org/a8Rgh –

+1

'$ constant'必须是一个带有常量名称的__string__。 –

回答

3
public static function isConstants($constant) { 
    $oClass = new ReflectionClass(__CLASS__); 
    $allConstants = $oClass->getConstants(); 
    if (isset($allConstants[$constant])) { 
     echo $allConstants[$constant]; 
    } else { 
     echo ''; 
    } 
}