PHP:将全局变量传递给函数吗?

时间:2019-11-15 12:17:33

标签: php

有代码:

<?php
$pamiClient = new PamiClient($options);
$pamiClient->open();
$temp = 42;
$pamiClient->registerEventListener(

    function (EventMessage $event ) 
    {
        if ($event instanceof VarSetEvent) {
            if ($varName == 'CALLID') {
                $temp = 43;
                echo "Temp from CALLID: " , $temp, "\n";
            }

            if ($varName == 'BRIDGEPEER') {
                echo "Temp from BRIDGPEER: " , $temp, "\n";
            } 
        }  
    }
);

while(true) {
    $pamiClient->process();
    usleep(1000);
}

$pamiClient->close();
?>

如何将$ temp传递给函数(EventMessage $ event),以便在  if ($varName == 'CALLID'){}节中可以看到if ($varName == 'BRIDGEPEER') {}-节?

2 个答案:

答案 0 :(得分:4)

您可以inherit variables from the parent scopeuse一起使用,例如:

function (EventMessage $event ) use ($temp)
{
   // to do something
}

答案 1 :(得分:1)

使用全局。

例如:

<?php

$varName = "foo";

function test() {
   global $varName;

   if ($varName == "foo") { ... }
}

了解更多:https://www.php.net/manual/en/language.variables.scope.php