harp1814
harp1814

Reputation: 1658

PHP: pass global variable to finction?

There is code:

<?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();
?>

How to pass $temp to function (EventMessage $event), so changes are made in if ($varName == 'CALLID'){} -section may be seen in if ($varName == 'BRIDGEPEER') {} section ?

Upvotes: 0

Views: 55

Answers (2)

Maksym Fedorov
Maksym Fedorov

Reputation: 6456

You can inherit variables from the parent scope with use, for example:

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

Upvotes: 4

Ika Balzam
Ika Balzam

Reputation: 236

Use global.

For example:

<?php

$varName = "foo";

function test() {
   global $varName;

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

Read more: https://www.php.net/manual/en/language.variables.scope.php

Upvotes: 1

Related Questions