doushi3202 2016-05-05 06:50
浏览 81
已采纳

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.

  • 写回答

3条回答 默认 最新

  • douaoj0994 2016-05-05 06:54
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器