php变量范围排队

时间:2016-05-05 06:50:03

标签: php scope visibility

首先是代码:

<?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,每个函数将在同一时间运行,全局变量将每秒更改,这不是我想要的。相反,我需要每个线程都使用自己的&#34; local&#34;全局测试变量。

3 个答案:

答案 0 :(得分:1)

您还需要在此使用global

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

但是在最后一次check_test();函数调用时出现问题,您将获得与{3}相同的$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

答案 1 :(得分:1)

在功能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();

Working example

答案 2 :(得分:0)

尝试下面的代码,你将在这里得到你想要的输出我已经改变了最后我调用了run方法,并且在run方法中我检查了参数是否为空然后在全局变量中设置“nothing”字,如果参数中有一些值则在全局测试变量中设置该值。尝试以下代码可能对您有所帮助。

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