在PHP中调用函数(带参数)中的函数

时间:2014-10-14 22:24:18

标签: php arrays function session session-variables

我正在构建一个从POST方法捕获信息的系统,并将它们添加到PHP $_SESSION中。我想要遵循的基本逻辑是:

  1. 检查方法并调用相关功能
  2. 通过函数
  3. 检查$_SESSION数据是否已存在
  4. 通过函数检查$post_id变量是否已经在$_SESSION的数组中
  5. 根据这些函数的结果,添加到数组,创建新数组或不执行任何操作
  6. 到目前为止,这是我编写的用于处理此逻辑的代码。我希望首先让add_to_lightbox()函数正常工作,并在之后转移到另外两个函数。

    session_start();
    
    // set variables for the two things collected from the form
    $post_id = $_POST['id'];
    $method = $_POST['method'];
    // set variable for our session data array: 'ids'
    $session = $_SESSION['ids'];
    
    if ($method == 'add') {
      // add method
      add_to_lightbox($post_id, $session);
    } elseif ($method == 'remove') {
      // remove method
      remove_from_lightbox($post_id);
    } else ($method == 'clear') {
      // clear method
      clear_lightbox();
    }
    
    function session_exists($session) {
      if (array_key_exists('ids',$_SESSION) && !empty($session)) {
        return true;
        // the session exists
      } else {
        return false;
        // the session does not exist
      }
    }
    
    function variable_exists($post_id, $session) {
      if (in_array($post_id, $session)) {
        // we have the id in the array
        return true;
      } else {
        // we don't have the id in the arary
        return false;
      }
    }
    
    function add_to_lightbox($post_id, $session) {
      if (!session_exists($session) == true && variable_exists($post_id, $session) == false) {
        // add the id to the array
        array_push($session, $post_id);
        var_dump($session);
      } else {
        // create a new array with our id in it
        $session = [$post_id];
        var_dump($session);
      }
    }
    

    它一直处于add_to_lightbox()并且每次跟随array_push($session, $post_id);的状态。我不确定我编写的代码是否可能是因为嵌套函数,以及我如何重构它以使函数正常工作。

1 个答案:

答案 0 :(得分:1)

之前的更正,似乎$ session是一个id数组..

您遇到的问题是您正在add_to_lightbox函数中修改该数组的本地副本。您不需要将变量专门实例化为数组,只需使用以下内容即可。

$_SESSION['ids'][] = $post_id;