php变量范围quetion


php variable scope quetion

下面是第一个代码:

<?php
$test = 'nothing';
function check_test(){
    global $test;
    echo 'The test is '.$test.''n';
}

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

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

check_test();

在Python中,AFAIK是可行的,因为它将变量搜索到更高的范围,但在php中看起来它的工作方式不同。所以问题来了:我如何才能实现这种行为——所以函数将使用第一个变量的出现,而不会从更高的范围级别开始观察。在这个例子中,我想要得到输出。

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

但只得到

The test is nothing

共4次。

意味着使用了第一个变量声明。非常感谢您对此提出的任何建议!

这不是重复的,我理解范围的概念,我在问是否有可能在这个片段中实现某些行为。

UPD:我不能使用所提出的方法,因为我们使用pthreads,每个函数将在同一时间运行,全局变量将每秒更改一次,这不是我想要的。相反,我需要每个线程都使用自己的"本地"全局测试变量。

您还需要在此处使用global

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

但当最后一次调用check_test();函数时,会出现一个问题,即您将获得与第三次调用相同的$test值。

示例:

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

建议:

因此,如果您真的想获得如图所示的输出,则需要向check_test()函数传递一个参数。

示例:

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

在函数run中,您将$lala设置为局部参数,而不是全局$test = 'nothing'

我想要这个:

$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}'r'n";
}
function run($param){
    check_test($param);
}
check_test();
check_test('Test 2');
check_test('Test 3');
check_test();

工作示例

试试下面的代码,你会在这里得到你想要的输出。我最后更改了我调用的run方法,在run方法中,我检查了参数是否为空,然后在全局变量中设置"none"字。如果参数中有一些值,然后在全球测试变量中设置该值。试试下面的代码,也许对你有帮助。

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