Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从异步PHP返回值_Php_Asynchronous - Fatal编程技术网

从异步PHP返回值

从异步PHP返回值,php,asynchronous,Php,Asynchronous,我想从PHP中的异步函数返回一个值。。。我在这里使用icicle.io,但我很乐意使用任何东西,只要它能满足我的需求!无论如何,下面是一些代码 <?php require __DIR__ . '/vendor/autoload.php'; use Icicle\Coroutine\Coroutine; use Icicle\Loop; function getArray($int) { yield array ($int, $int + 1, $int + 2); } fu

我想从PHP中的异步函数返回一个值。。。我在这里使用icicle.io,但我很乐意使用任何东西,只要它能满足我的需求!无论如何,下面是一些代码

<?php

require __DIR__ . '/vendor/autoload.php';

use Icicle\Coroutine\Coroutine;
use Icicle\Loop;

function getArray($int) {
    yield array ($int, $int + 1, $int + 2);
}

function getArrays() {
    $numbers = array (1, 4, 7);
    $results = array();

    foreach ($numbers as $number) {
        array_push($results, (yield(getArray($number))));
    }

    yield call_user_func_array('array_merge', $results);
}

$coroutine = new Coroutine(getArrays());

$data = $coroutine->then(
    function ($result) {
        $data = print_r($result, true);
        return "Result: {$data}\n";
    },
    function (Exception $e) {
        echo "Error: {$e->getMessage()}\n";
    }
)->done(function ($value) {
    echo $value;
});

Loop\run();
然后从我的酷软件中,我可以调用sync(),就好像它是一个同步函数一样,幸福地不知道幕后正在进行的异步把戏


有没有人这样做过,或者对我如何做有什么建议?目前,我想到的最好的方法是(ab)使用输出缓冲区&
serialize()
/
unserialize()
函数,但由于我这么做完全是为了提高性能,这似乎有点倒退

您可以使用
wait()
方法同步等待可等待的解决方案(包括协同路由)。此方法会勾选事件循环,直到解决协同路由。这意味着您的
sync()
函数可以简单地对coroutine对象调用此方法并返回结果

function sync() {
    $coroutine = new Coroutine(getArrays());
    return $coroutine->wait();
}
function sync() {
    $coroutine = new Coroutine(getArrays());
    return $coroutine->wait();
}