将回调值分配给变量?

时间:2017-04-04 16:54:08

标签: php

我有问题将回调值赋给变量。

下面的示例代码,没有任何问题。它将显示在浏览器上。

Service::connect($account)->exec(['something'], function ($line) {
   echo $line . PHP_EOL;
});

但是,我想为json响应分配变量。

这不起作用:

$outout = null;

Service::connect($account)->exec(['something'], function ($line) use ($outout) {
      $outout = $outout . = $line;
);

echo $outout;

$outout仍为空。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

如果您希望将$outout更改为功能范围之外,请将&传递给reference。您可以通过在函数调用中添加$outout = ''; Service::connect($account)->exec(['something'], function ($line) use (&$outout) { $outout = $outout . = $line; ); 来实现此目的。

    public static void Main()
{
    int red = 0;
    int green = 255;
    int blue = 0;

    //convert to 5-bit values
    red = red >> 3;
    green = green >> 3;
    blue = blue >> 3;

    //position them correctly
    red = red << 8;
    blue = blue << 2;       
    int greenH = green >> 3;
    int greenL = green << 13;

    //add the 'always on' bit
    int fiveBitRGB = 0x80;

    //or them all together
    fiveBitRGB = fiveBitRGB | red | blue | greenH | greenL;
    fiveBitRGB = fiveBitRGB & 0xffff;

    Console.Write("Hex: {0:X4}", fiveBitRGB);
}

答案 1 :(得分:1)

您需要将其作为参考传递以更改其值。在&语句的变量前使用use

$outout = null;

Service::connect($account)->exec(['something'], function ($line) use (&$outout) {
      $outout = $outout . = $line;
);

echo $outout;