douchongbang6011 2011-07-29 10:22
浏览 26
已采纳

全球不工作

I have a file in PHP with a large array and a function that searches the array.

Heres the code:

$details = array(

  array('fieldID'=>'0','fieldCaption'=>'Address 1','fieldType'=>'text','fieldName'=>'addr1','fieldRequired'=>'1'),
  array('fieldID'=>'1','fieldCaption'=>'Address 2','fieldType'=>'text','fieldName'=>'addr2','fieldRequired'=>'1'),
  .
  .
  .
);

if(!function_exists('find_detail'))
{
  function find_detail($fieldName)
  {
    global $details;
    var_dump($details); // NULL

    foreach ($details as $detail)
    {
      if($detail['fieldName'] == $fieldName)
      {
        return $detail['fieldID'];
      }
    }
    return false;
  }
}

This sits inside a single helper file and calling var_dump($details); is returning NULL. I suspect an issue with scoping.

Many Thanks

-- edit --

This is bad practice and the best approach to handling this would be (as @Gordon stated) to pass the details array into the function. (Warning: There exist better ways of doing this, for example using array_filter)

if(!function_exists('find_detail_by_field_name'))
{
  function find_detail_by_field_name($details, $fieldName)
  {
    foreach ($details as $detail)
    {
      if($detail['fieldName'] == $fieldName)
      {
        return $detail['fieldID'];
      }
    }
    return false;
  }
}

And provide a way to get the details, wrapping details in a function would provide many benefits such as caching, change of source etc.

function get_details() 
{
   static $details = array(...)
   return $details;
}
  • 写回答

3条回答 默认 最新

  • dongmao7195 2011-07-29 10:26
    关注

    If your function operates on that $details array, it should ask for that array in the function signature. Anything else is just hiding dependencies and is hard to debug and maintain (as you can see by the need to ask your question). So change it to

    function find_detail($fieldName, array $details)
    

    and foreach over the passed in array then.

    Also, since the function really returns the fieldId and not some detail, you might want to rename it to

    function findFieldIdByFieldName($fieldName, array $details)
    

    But to answer your question: you likely get this effect because you created the $details array outside the global scope, the topmost scope of your script. If you defined $details in a function or a method or if it is included in the scope of another function, it is not in the global scope.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改