为什么这个函数不修改数组的全局版本?

Why doesn't this function modify the global version of the array?

本文关键字:全局 版本 数组 修改 函数 为什么      更新时间:2023-09-26

我定义了一个我认为是全局作用域的变量。我想在类中的函数中修改相同的变量,然后稍后使用它作为json数据导出。

函数是由xataface api调用的,所以我不确定我是否可以通过函数签名来做一些像引用传递这样的事情。我想我可能会访问这个动作类的实例在javascript中嵌入php,但我不知道如何向api请求它,我也不相信它的生命周期。全局变量似乎是可行的方法。无论如何,我想知道:

  1. 为什么不是$dataset1的全局实例在函数内被修改?
  2. 为什么调用array_push不把任何东西放在数组上?
<?php
//non-dynamic data delcared in global scope. This is picked up later
//in a php block embedded into javascript
$dataset1 = array(array("label"=>"c120","data"=>"1"),
                  array("label"=>"c150","data"=>"10"),
                  array("label"=>"camp","data"=>"7"));
class actions_time_in_type
{
  function handle(&$params)
  {
    $this->app =& Dataface_Application::getInstance(); 
    //The Query
    $result = mysql_query("SELECT typeDes, total
                           FROM myTable", $this->app->db());
    //reserch leads me to believe that this *should* make all subsequent
    //references to $dataset1 use the global instance
    global $dataset1;
    //experimenting with appending more non-dynamic data
    //for some reason, this syntax does not seem to touch $dataset1 
    array_push($dataset1, array("label"=>"dv20","data"=>"1"));
    //This syntax is working, but $dataset1 is not the same as the global 
    //$dataset1. Prepending "global" here seems to crash the script
    $dataset1[] = array("label"=>"pa18","data"=>"5");
    while($row = mysql_fetch_assoc($result))
    {
       //append data to the array, again, this is not hitting
       //the global instance of $dataset1
       $dataset1[] = array("label"=>$row['typedes'],"data"=>$row['total']);
    }
    mysql_free_result($result); //Frees the result after finished using it           
    //diagnostic dump to see what we've got
    //This shows that we've constructed the dynamic data set, but it
    //seems to be scoped only to this function and does not make it into
    //javascript.
    var_dump($dataset1);
  }
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>
<script type="text/javascript">
$(function () {
   //This is getting only what was done original init of $dataset1, nothing that
   //happened in the function made a difference
   var dataset1 = <?php echo json_encode($dataset1); ?>;
});
</script>

看来这确实是执行顺序的问题。由于数据的操作发生在类定义中,而类定义又由api调用,因此似乎无法保证当操作数据时数据的全局定义将在范围内,或者当数据被进一步重用时它将被操作。

对于感兴趣的读者,我能够让api开发人员演示调用类内函数将javascript与api集成的正确方法:

https://groups.google.com/forum/!主题/xataface l6qBzxF1vrc