【问题标题】:global variable can't accessible inside the function函数内部无法访问全局变量
【发布时间】:2017-02-15 13:13:59
【问题描述】:

我需要从另一个函数访问全局变量。首先,我在一个函数中将值分配给全局变量。当我试图从另一个函数中获取该值时,它总是返回 null。这是我的代码

StockList.php

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

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

建议.php

<?php

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

   $stk->getValue();

?>

提前致谢。

【问题讨论】:

  • 为什么这需要是一个全局变量?为什么不能简单地使用类属性?
  • 您不能在创建全局变量之前访问它。话虽如此,请尽量避免使用全局变量。
  • 我认为全局变量应该在类内
  • 在您的示例中,您永远不会调用 report()。所以它没有设置变量。如果你调用它,它会按预期工作3v4l.org/A0HCY

标签: php global-variables global


【解决方案1】:

伙计,很难理解你在做什么,因为你说你在 index.php 中调用了 report() 无论如何,在处理类时,要设置变量值,标准过程如下:

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

  public function getValue(){
     return $this->current;
  }
}

无论何时你想使用该类:

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

这是 OOP 的基本思想,这种方法的好处是:

  1. 您可以动态设置 $_current 的值。

  2. 您的 getValue() 函数并非专用于打印变量的值,这就是为什么您只能使用该函数来获取值,然后对它做任何您想做的事情。

【讨论】:

  • report() 在 index.php 中被调用。 getValue() 函数在 Ajax 中调用。
  • 你能以某种方式显示 report() 调用的代码吗?或者确保在创建类实例之后和调用 getValue() 之前调用了 report();
  • @balaraman 听起来您希望跨页面保留值更改。如果是这种情况,您应该为此使用会话。否则你必须每次都设置值
猜你喜欢
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多