为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
呼啦一阵风 2023-11-03 16:03:40
您可以通过以下方式执行此操作: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}
查看完整描述

3 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

检查一个常量是否由她的名字定义:


defined('CONSTANT');

检查是否有任何值是字符串:


is_string(CONSTANT);

从逻辑上讲,如果它不是常量,那么它只是一个字符串。


要检查是否是常量,您必须在字符串中传递常量名称。您还可以使用 检查是否存在具有相同值的常量get_defined_constants(),但您不会知道是否是相同的常量。


define('MYCONST', "THE VALUE");

function exists_a_constant($value)

{

    $constants = get_defined_constants(true);

    return in_array($value, $constants['user']); // true if finds or false if not

    // return array_search($value, $constants['user']);    //Will return the key (name of the constant)

}


function checkVars($var)

{

    if (exists_a_constant($var)) {

        echo "exists a constant";

    } else {

        echo "not";

    }

}


checkVars(MYCONST);

// exists a constant

checkVars('MYCONST');

// not

checkVars("THE VALUE");

// exists a constant

checkVars("random string");

// not


查看完整回答
反对 回复 2023-11-03
?
慕仙森

TA贡献1827条经验 获得超7个赞

您将使用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

}


查看完整回答
反对 回复 2023-11-03
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

我做了一些更改并且有效。


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';

}


查看完整回答
反对 回复 2023-11-03
  • 3 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信