PHP:防止函数返回值?
我如何确保正在调用 startProcess();
函数,但不停止 myFunction()
的执行。我猜想有一种方法可以调用函数并阻止它返回它的值,从而实现这一点?
伪代码:
function myFunction() {
startProcess();
return $something;
}
function startProcess() {
sleep(5);
// Do stuff that user doesn't should have to wait for.
}
How could I make sure that the startProcess();
function is being called, but without halting the execution for myFunction()
. I'll guess that there's a way to call a function and prevent it from returning it's value to thereby accomplishing this?
Pseudo-code:
function myFunction() {
startProcess();
return $something;
}
function startProcess() {
sleep(5);
// Do stuff that user doesn't should have to wait for.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你做不到。 PHP 中有一些函数允许异步 I/O,但没有像您所需要的并发性那样。
现有无语言支持的原因是 PHP 被设计为执行短期脚本,而并发性由 HTTP 守护进程管理。
另请参阅:
cur_mult_init
pcntl_fork
(仅限 UNIX)You can't do it. There are some a few functions in PHP that allow async I/O, but nothing like the concurrency you require.
The reason for existing no language support is that PHP is designed to execute short-lived scripts, while the concurrency is managed by the HTTP daemon.
See also:
cur_mult_init
pcntl_fork
(unix only)为了对 Artefecto 的答案做一点补充,有些人试图重新创建一种线程情况。你可以使用谷歌找到一些关于它的信息,但我怀疑它会有帮助,因为它太实验性而且可能相当不可靠。
找到一个可能对您有帮助的链接。
To make a small addition to Artefecto's answer, there are some people who've attempted to recreate a sort of threads situation. You can find some information on it using google, but I doubt it'll be helpful as it's just too experimental and probably pretty unreliable.
Found one link that might be helpful for you.
据我从你的问题和标签中可以看出,你想要进行一些后台处理,本质上意味着多线程。
不幸的是,PHP 不这样做。有一些 IO 函数是异步的,但通常在 PHP 中不能进行并发处理。
As far as I can tell from your question and tags, you want to do some background processing, meaning, essentially, multiple threads.
Unfortunately, PHP doesn't do this. There are some IO functions that are asynchronous, but in general you cannot do concurrent processing in PHP.
你想要 startProcess() 做什么?有很多方法可以让用户不必等待。
电子邮件就是一个很好的例子:运行 mail() 的线程一直旋转,直到消息被接受或拒绝;您不希望用户必须等待。因此,您将任务排队,然后在 cron 上处理队列。
What is it you want startProcess() to do? There are many ways to keep the user from having to wait.
Emails are a good example: the thread that runs mail() spins until the message is accepted or rejected; you don't want a user to have to wait for that. So you queue up the task, and then process your queue on cron.
您是否查看过 Gearman 来外包此类后台任务?
Have you looked at Gearman for farming out this kind of background task?
我将在这里尝试一下,但是这个功能看起来可以成为您总体目标的解决方案吗?
http://php.net/manual/en/function.register- shutdown-function.php
I'm going to take a shot in the dark here, but does this function look like it could be a solution for your overall goal ?
http://php.net/manual/en/function.register-shutdown-function.php