通过 Ajax 调用的 PHP 变量生命周期

发布于 2024-10-19 02:28:47 字数 768 浏览 2 评论 0原文

一旦垃圾收集器认为有必要,变量通常会被销毁,并且它们占用的内存会被释放。基本上,当前执行的脚本完成后不久,是吗?

现在,我对 Ajax 检索变量的生命周期感兴趣。

由于变量通常在它们运行的​​脚本完成后(即页面重新加载时)被清除,Ajax 也属于这一类吗?如果我有一个脚本从 PHP 接收一个胖 JSON 数组,并在使用完它后仅使用“arrayVar = null”清除 JS 变量,这是否足够?或者我应该取消设置创建返回数组的 PHP 变量吗?例如:

// PHP CODE
<?
public function some_kind_of_ajax_called_action() {

    $someClass = new MyClass();
    $someArray = $someClass->getRequestedData();
    $arrayForReturning = array();

    foreach ($someArray as $element) {
        ($currentUser == "admin")?($arrayForReturning[] = $element):null;
    }

    die(json_encode($arrayForReturning));
}
?>

包含... ...会更好吗

unset($someClass);
unset($someArray);

在 die() 调用之前 ?这会节省内存吗,无论多少?

干杯

Variables typically get destroyed and the memory they've occupied is freed as soon as the garbage collector deems it necessary. Basically, pretty soon after the currently executed script is finished, yeah?

Now, I'm interested in the lifetime of Ajax retrieved variables.

Since variables are typically purged after the script they're running in is finished, that is, on page reload, does Ajax fall into this category as well? If I have a script that receives a fat JSON array from PHP, and clear only the JS variable with "arrayVar = null" after I'm done using it, is that enough? Or should I unset the PHP variables which created the returned array as well? For example:

// PHP CODE
<?
public function some_kind_of_ajax_called_action() {

    $someClass = new MyClass();
    $someArray = $someClass->getRequestedData();
    $arrayForReturning = array();

    foreach ($someArray as $element) {
        ($currentUser == "admin")?($arrayForReturning[] = $element):null;
    }

    die(json_encode($arrayForReturning));
}
?>

Would it be better to include...

unset($someClass);
unset($someArray);

...before the die() call? Would this conserve memory, regardless of how little?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡墨 2024-10-26 02:28:47

PHP 部分在处理您的 AJAX 请求时就完成了,直到页面重新加载。是否将其保存在 JS 变量中并不重要。他们没有联系。

PHPs part is done the moment it has served your AJAX request and not until page reload. It doesn't matter whether you hold it in a JS variable. They aren't connected.

A君 2024-10-26 02:28:47

我不明白为什么这是必要的,因为 AJAX 请求与通常的 HTTP 请求没有什么不同,只是浏览器对它的响应的处理方式不同。

I don't see a reason why this should be necessary, as an AJAX-request is not different from a usual HTTP-request, just that its response is handled differently by your browser.

宁愿没拥抱 2024-10-26 02:28:47

这两个变量都将在脚本末尾取消设置,就像任何其他页面一样。

顺便说一句,您也可以使用 unset($someClass,$someArray) 因为它需要多个输入

Both those variables would unset at the script end, in the same way as any other page.

Incidentally, you could also use unset($someClass,$someArray) since it takes multiple inputs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文