【问题标题】:Calling functions from within functions (with arguments) in PHP在 PHP 中从函数内部调用函数(带参数)
【发布时间】:2014-10-15 06:32:30
【问题描述】:

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

  1. 检查方法并调用相关函数
  2. 通过函数检查$_SESSION数据是否已经存在
  3. 通过函数检查$post_id变量是否已经在$_SESSION的数组中
  4. 根据这些函数的结果,添加到数组、创建新数组或什么都不做

到目前为止,这是我为处理此逻辑而编写的代码。我希望首先让 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);。由于嵌套函数,我不确定我编写的这段代码是否可行,以及如何重构它以使功能正常工作。

【问题讨论】:

  • array_key_exists('ids',$_SESSION) 你可以只做isset($_SESSION['ids'])!session_exists($session) == true,只是!session_exists($session)variable_exists($post_id, $session) == false 只是!variable_exists($post_id, $session)。同样array_push($session, $post_id); 不修改原始数组,只修改其本地副本。使用function add_to_lightbox($post_id, &$session)$session = [$post_id]; 不会更新$_SESSION 数组。
  • 效果很好,谢谢。

标签: php arrays function session session-variables


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2020-08-03
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2015-01-22
    相关资源
    最近更新 更多