doubishi8303 2014-10-14 22:24
浏览 48
已采纳

在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.

  • 写回答

1条回答 默认 最新

  • douchen7555 2014-10-14 22:32
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab