dtebrq0245 2015-09-01 00:11
浏览 109
已采纳

PHP如何在函数中定义局部变量?

I have this code:

  require_once('../config.php');
  function ha(){
     global $user; /* THIS I NEED TO DEFINE LOCAL ONLY ACCESS FROM THIS FUNCTION */
     return $user;
}

echo ha();

echo $user; /* GLOBAL VARIABLE VALUE */

So how to define in function local variable that will be accessed throught inside function ha()? So the outout from the echo ha(); will be value $user that is stored in config.php, and last line echo $user needs to be empty on echo...when i define in function static $user i get empty value...so how to define in php static value of variable that is read from config.php and access value only in function?

  • 写回答

4条回答 默认 最新

  • dongzhong2018 2015-09-01 00:13
    关注
    function ha(){
        global $user;
        $user2 = 'abc'; //no prefix whatsoever
    
        echo $user; //prints global $user
        echo $user2; //prints local $user2
    }
    

    how to define in php static value of variable that is read from config.php and access value only in function?

    It's all about variable scope , if you want a variable to be defined in config file and only be readable from within a function, then your current approach is incorrect. Anything declared in main scope (such as config file loaded in main scope) will be accesible from nearly anywhere in the code. If you don't want variables to be accessed otherwise than through ha() then they need to be defined within ha().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决