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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c