猿问

PHP 在验证之前检测它是 CONSTANT 还是 STRING

您可以通过以下方式执行此操作:


function count_array_values($my_array, $match) 

{

    $count = 0; 

    foreach ($my_array as $key => $value) 

    { 

        if ($value == $match) 

        { 

            $count++; 

        } 

    }    

    return $count; 

$array = ["hello","bye","hello","John","bye","hello"];

$output =[];


foreach($array as $a){

    $output[$a] = count_array_values($array, $a); 

}

arsort($output);

print_r($output);

你会得到类似的输出


Array ( [hello] => 3 [bye] => 2 [John] => 1 )我正在开发一个验证变量和常量的函数。


function checkVars($var){

 if(isConstant($var)){ <--here is my problem, how do I check if its a Constant and or a string?

  return defined($var);

 }else{

  //use other functions to check if its a valid variable

 }

}

有没有办法检查它是字符串还是常量?


编辑: 这背后的想法是节省重复任务的代码行,例如:


if(defined('CONS')){

 if(CONS > 0 && CONS !== false){

  //and so on..

 }

}

这只是一个示例,但您可以使用 4 行代码来验证常量或变量以满足特定应用程序的需求。


这个想法是通过返回 true 或 false 的单个函数调用来保存所有工作:


if(isValid('CONS')){

 //do stuff on true

}else{

 //do stuff on false

}


呼啦一阵风
浏览 146回答 3
3回答

慕哥9229398

检查一个常量是否由她的名字定义:defined('CONSTANT');检查是否有任何值是字符串:is_string(CONSTANT);从逻辑上讲,如果它不是常量,那么它只是一个字符串。要检查是否是常量,您必须在字符串中传递常量名称。您还可以使用 检查是否存在具有相同值的常量get_defined_constants(),但您不会知道是否是相同的常量。define('MYCONST', "THE VALUE");function exists_a_constant($value){&nbsp; &nbsp; $constants = get_defined_constants(true);&nbsp; &nbsp; return in_array($value, $constants['user']); // true if finds or false if not&nbsp; &nbsp; // return array_search($value, $constants['user']);&nbsp; &nbsp; //Will return the key (name of the constant)}function checkVars($var){&nbsp; &nbsp; if (exists_a_constant($var)) {&nbsp; &nbsp; &nbsp; &nbsp; echo "exists a constant";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo "not";&nbsp; &nbsp; }}checkVars(MYCONST);// exists a constantcheckVars('MYCONST');// notcheckVars("THE VALUE");// exists a constantcheckVars("random string");// not

慕仙森

您将使用defined()来测试该常量是否存在并已定义。然后使用is_string()withconstant()来判断常量是否是字符串。我假设您正在使用,return因为此条件是函数的一部分:if(defined($constantName) and is_string(constant($constantName))) {    return constant($constantName);} else {    // other code}运行以下测试我可以看到返回了“bar”:define("FOO", "bar");$constantName = "FOO";if(defined($constantName) and is_string(constant($constantName))) {    echo constant($constantName); // 'bar'} else {    // other code}

繁星淼淼

我做了一些更改并且有效。get_define_constants 获取一个包含所有已定义常量的数组,然后我使用 array_key_exists 来检查您传递的常量是否在数组中。define('FOO','bar');function exists_a_constant($value){    $constants = get_defined_constants();    return array_key_exists($value,$constants); }if(exists_a_constant('FOO')){    echo 'defined';}else{    echo 'not defined';}
随时随地看视频慕课网APP
我要回答