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

时间:2014-05-10 04:37:33

标签: javascript php

我在全球范围内定义了一个变量。我想修改一个存在于类中的函数内的相同变量,然后使用它作为json数据导出。

该函数由xataface api调用,所以我不确定我是否可以使用函数签名来执行像引用一样的操作。我以为我可能会在javascript嵌入式php中访问此动作类的实例,但我不知道如何向api请求它,我也不知道它的生命周期。似乎全局变量可能是要走的路。无论如何,我想知道:

  1. 为什么$ dataset1的全局实例不是在函数内修改的实例?
  2. 为什么对array_push的调用没有在任何一个数组上放置任何东西?
  3. <?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>
    

1 个答案:

答案 0 :(得分:0)

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

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

https://groups.google.com/forum/#!topic/xataface/l6qBzxF1vrc