【问题标题】:How to create functions in PHP如何在 PHP 中创建函数
【发布时间】:2018-11-28 07:58:49
【问题描述】:

我是 PHP 新手,我创建了一个 PHP 会话脚本,该脚本在 30 分钟不活动后超时,并且运行良好。

但是,我想将它放在一个函数中并在需要它的页面中调用它以避免 DRY。我怎样才能做到这一点?

PS:我创建的函数抛出“未定义索引”错误。 代码片段如下:

$_SESSION['LAST_ACTIVITY'] = time();
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION[$'LAST_ACTIVITY'] > 5)) {
        // last request was more than 30 minutes ago
        session_unset();
        session_destroy();
        header('Location: index.php');
          // exit;              
    }

【问题讨论】:

  • 检查docs
  • 我已经有了,但它不起作用。我也搜过网
  • 那么请出示您的功能码。你发的不是功能,不分享我们帮不了你。
  • 这里还有一个错字:$_SESSION[$'LAST_ACTIVITY'] 应该是 $_SESSION['LAST_ACTIVITY']。而且你应该在最后而不是在开始时分配它($_SESSION['LAST_ACTIVITY'] = time();),否则你的条件将始终评估为假。

标签: php function session


【解决方案1】:
function callMe() {
    $_SESSION['LAST_ACTIVITY'] = time();
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 5)) { 
        // you should not use $ with array indexes/keys

        // last request was more than 30 minutes ago
        session_unset();
        session_destroy();
        header('Location: index.php');
          // exit;              
    }
}

PS:我创建的函数抛出“未定义索引”错误。代码的sn-p如下:

在你给定的 sn-p 中,一个函数是不可见的,它只是带有条件块的过程代码。

顺便说一下,你应该先使用搜索引擎。

这是用户定义函数文档的链接:

http://php.net/manual/en/functions.user-defined.php

【讨论】:

  • 我已经能够修复它。谢谢
  • @jessebrite 您可以选择接受的答案。如果它确实解决了您的问题,请将此答案标记为已接受的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2018-01-14
  • 1970-01-01
  • 2022-08-16
  • 2015-07-22
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多