PHP pass variable by referenced's issue in closure function

时间:2016-08-30 09:41:38

标签: php

<?php
/**
 * Created by PhpStorm.
 * User: james
 * Date: 8/30/16
 * Time: 12:28 PM
 */
include_once './vendor/autoload.php';
use Workerman\Worker;
use Workerman\Lib\Timer;

$active_socket = [];

$coap_wk = new Worker('Coap://0.0.0.0:50008');

//print_r($coap_wk);

$http_wk = new Worker('http://0.0.0.0:8080');

$http_wk->count = 4;

//
$http_wk->onWorkerStart = function ($worker) use(&$active_socket)
{
    //global $active_socket;
    //echo "Worker's id ={$worker->id}\n";
    //$active_socket = $active_socket;
    echo count($active_socket);
    if ($worker->id === 3)
    {
        //$socket = $active_socket;

        Timer::add(5, function() use (&$active_socket) {
            var_dump(count($active_socket)); //
            //echo " 4 eggs, 4 process.\n";
            //print_r(count($active_socket));
        });

    }
};

$http_wk->onMessage = function ($connect, $data) use(&$active_socket)
{
    //global $active_socket;
    $active_socket[] = $connect;
    //var_dump($data);
    echo "onmessage";
    var_dump($active_socket);
    Timer::add(5, function() use (&$active_socket) {
        var_dump(count($active_socket));
        //echo " 4 eggs, 4 process.\n";
        //print_r(count($active_socket));
    });
    $connect->send(rand(999, 99999999));
};

Worker::runAll();

** Here is my problem:**

I create two callback closure function and pass the same variable by reference.

When I receive request, I will change the variable $active_socket on the second callback function, and var_dump the number of $active array.

According to PHP's manual, if you pass a variable by reference. It means the same memory address, but in onWorkerStart's callback function, I can not get $active_socket's value changed by onMessage.

Does anyone can tell me what happen? Or something I missunderstand PHP's usage of callback function and variable pass by referenced.

Thank you sincerecely.

1 个答案:

答案 0 :(得分:0)

密钥是SameSite,这意味着有4个进程。 流程之间的变量是分开的。 如果SELECT mm.adi , YEAR(sb.tarih) AS yil , COUNT(1) AS satisSayisi FROM Marka mm JOIN Model mo ON mo.markaId = mm.markaId JOIN Araba aa ON aa.modelId = mo.modelId JOIN SatisSatirlari ss ON ss.arabaId = aa.arabaId JOIN SatisBaslik sb ON sb.satisId = ss.satisId WHERE sb.tarih >= '2017-01-01' AND sb.tarih < '2018-01-01' GROUP BY mm.adi , YEAR(sb.tarih) 它会运作良好。