drls2738 2011-10-14 15:30
浏览 67
已采纳

PHP:从函数内部声明具有全局范围的变量[duplicate]

Possible Duplicate:
Declaring a global variable inside a function

Is it possible to declare variable with global scope from inside a function?

NOTE: I don't want to receive the value of a previously declared variable outside the function. But to have the values of the variables declared inside the function working outside the function scope.

I a way that if I have these variables declared inside a function:

function variables($n){
    $a=1+$n;
    $b="This is number +$n";
}

I could echo them outside the function:

variables(1);
echo $a;
echo '
';
echo $b;

2
This is number 1

I know I could achieve it returning an array from the function but... I'd like to be sure I could otherwise.

I saw nothing here: http://php.net/manual/en/language.variables.scope.php

Thanks.

  • 写回答

1条回答 默认 最新

  • duankui3838 2011-10-14 15:34
    关注

    You can read elsewhere about why globals are bad, so I'll just stick to the question. You can use the global keyword for this. The same applies if you want to read a global from inside a function.

    function variables($n){
        global $a,$b;
        $a=1+$n;
        $b="This is number +$n";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝