dqdl6469 2017-02-15 13:13
浏览 335

全局变量无法在函数内部访问

I need to access the global variable from another function. First I have assigned the value to global variable in one function. When I am trying to get that value from another function, it always returns null. Here my code is

StockList.php

<?php 
 $_current;
class StockList
{
  public function report(){
    global $_current;
    $_current = 10;
  }

  public function getValue(){
     print_r($GLOBALS['_current']);
  }
}
?>

Suggestion.php

<?php

   include ("StockList.php");
   $stk = new StockList();  

   $stk->getValue();

?>

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doujimiao7480 2017-02-15 13:18
    关注

    Man, its hard to understand what are you trying to do as you said you have called report() in your index.php Anyways, when dealing with classes, to set variable values, standard procedure is as following:

    class StockList
    {
      public $_current;
      public function setValue($value){
        $this->current = $value;
      }
    
      public function getValue(){
         return $this->current;
      }
    }
    

    And after whenever you wanna use the class:

    <?php
       include ("StockList.php");
       $stk = new StockList();  
       $stk->setValue(10);
       $_current = $stk->getValue();
       var_dump($_current);
    ?>
    

    This is basic idea of OOP, benefits of this approach are:

    1. You can dynamically set value of $_current.

    2. Your getValue() function is not dedicated for printing the value of the variable, thats why you can use that function only for getting the value and then do whatever you want with it.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大