php变量范围问题

Here's the code first:

<?php

$test = 'nothing';

function check_test(){
    global $test;

    echo 'The test is '.$test.'
';

}


function run($lala){
    $test = $lala;
    check_test();
}


check_test();

run('Test 2');
run('Test 3');


check_test();

AFAIK in Python it would work, because it searches variables to upper scope, but looks like it works different in php. So here is the question: how can I achieve that behaviour - so function will use first variable occurance and won't start looking from the higher scope-level. In this example I wanted to get output.

The test is nothing
The test is Test 2
The test is Test 3
The test is nothing

But got only

The test is nothing

for 4 times.

Means that very first variable declaration was used. Much appreciate with any suggestions to this!

This is not duplicate, I understand the conception of scope, I'am asking about is it possible to achieve certain behaviour in this snippet.

UPD: I can't use proposed methods because we use pthreads and each function will run in the same time and global variable will be changed every second and that's not what I want. Instead I need that every thread will be using its own "local" global test variable.

You need to use global here also.

function run($lala){
    global $test = $lala;
    check_test();
}

but there is a problem when the last check_test(); function call then you will get he same value of $test as for 3rd one.

Example:

The test is nothing
The test is Test 2
The test is Test 3
The test is Test 3

Suggestion:

So if you really want to get the output like you show the you need to pass a parameter to your check_test() function.

Example:

function check_test($arg= null) {
    global $test;

    $arg= ($arg== null) ? $arg: $test;

    echo "The test is ".$arg."<br/>";
}

function run($par){
    check_test($par);
}

The test is nothing
The test is Test 2
The test is Test 3
The test is nothing

In function run you are setting $lala to local parameter, not for global $test = 'nothing'.

I would to like this:

$test = 'nothing';

function check_test($param = null) {
    global $test;

    // if no parameter passed, than use global variable.
    $param = is_null($param) ? $param : $test;

    echo "The test is {$param}
";
}

function run($param){
    check_test($param);
}

check_test();
check_test('Test 2');
check_test('Test 3');
check_test();

Working example

Try below code you will get your desired output here i have change the at last i called run method and in run method i checked if parameter is empty then set "nothing" word in global variable if there is some value in parameter then set that value in global test variable. try below code may it helpful for you.

<?php
$test = 'nothing';

function check_test(){
    global $test;

    echo 'The test is '.$test.'<br/>';

}


function run($lala){

   $GLOBALS['test'] = !empty($lala) ? $lala : 'nothing';
    check_test();
}


check_test();

run('Test 2');
run('Test 3');
run('');
?>