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

I’m building a system that captures info from a POST method and adds them into a PHP $_SESSION. The basic logic I want to follow is:

  1. Check the method and call the relevant function
  2. Check if $_SESSION data already exists via a function
  3. Check if the $post_id variable is already in the $_SESSION's array via a function
  4. Based on the outcomes on these functions, add to the array, create a new array, or do nothing

Here is the code I have written to handle this logic so far. I am looking to get just the add_to_lightbox() function working first, and will move onto the other two after.

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);
  }
}

It's stuck in a state where it's always getting to add_to_lightbox() and following the array_push($session, $post_id); each time. I’m unsure whether this code I’ve written is possible because of the nested functions, and how I can refactor it to get the functionality working.

Correction from before, seems like $session is an array of ids..

The problem you are having is that you're modifying the local copy of that array within add_to_lightbox function. You don't need to specifically instantiate the variable as an array, you can just use the following.

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