【问题标题】:PHP global variable is not changing [duplicate]PHP全局变量没有改变[重复]
【发布时间】:2015-08-30 03:17:04
【问题描述】:

我对 PHP 和全局变量有疑问。 在这段代码中:

  1. 在页面开始时,结果为:Test 123
  2. 点击后:ListBox1点击结果为:XXXXXXXX
  3. 点进去后:ListBox2Click结果是:Test 123错了!

有什么方法可以通过这种方式更改全局变量吗?它需要从“ListBox1Click”函数内部进行更改,并从“ListBox2Click”函数中的代码显示。

<?php
  require_once("rpcl/rpcl.inc.php");
  //Includes
  use_unit("forms.inc.php");
  use_unit("extctrls.inc.php");
  use_unit("stdctrls.inc.php");

  //Class definition

  class Page1 extends Page
  {
    public $Label8 = null;
    global $someVar;
    $someVar = "Test 123";
    $this->Label8->Caption = $someVar;

    function ListBox1Click($sender, $params)
    {
      global $someVar;
      $someVar = "XXXXXXXX";
      $this->Label8->Caption = $someVar;
    }
    function ListBox2Click($sender, $params)
    {
      global $someVar;
      $this->Label8->Caption = $someVar;
    }
  }

  global $application;

  global $Page1;

  //Creates the form
  $Page1=new Page1($application);

  //Read from resource file
  $Page1->loadResource(__FILE__);

  //Shows the form
  $Page1->show();

?>

感谢您的帮助

【问题讨论】:

  • 评论:你有一个额外的右括号}
  • 不要使用全局变量。曾经。尤其是在封装很重要的 OO 场景中。参数列表的存在是有原因的。使用它们。
  • 感谢您的建议,但问题是我需要存储一些变量,这些变量需要可以从两个 listBoxes OnClick 事件函数内部访问。但是现在,如上例,点击listBox2后,$someVar变为“Test 123”而不是“XXXXXXXX”
  • @wcale,我认为您想要实现的是存储解决方案(变量存储在两个请求之间),因此与全局无关。您的变量 $somevar 也可以是私有的,并通过以下方式访问:$this-&gt;somevar...
  • @wcale 请描述您对全局变量行为的期望?看起来您希望它们的值在独立的 http 请求之间传递。这种方式是行不通的。如果您想在 http 请求之间传递值,请参阅会话文档。

标签: php variables global


【解决方案1】:

您的解决方案可能如下所示:

<?php
  require_once("rpcl/rpcl.inc.php");
  //Includes
  use_unit("forms.inc.php");
  use_unit("extctrls.inc.php");
  use_unit("stdctrls.inc.php");

  //Class definition

  class Page1 extends Page
  {
    public $Label8 = null;
    private $someVar;

    public function __construct($application)
    {
        parent::__construct($application);

        //load from storage
        $this->someVar = $_SESSION['someVar'];
        $this->Label8->Caption = $this->someVar;


    }

    public function __destruct()
    {
          //save to storage
          $_SESSION['someVar'] = $this->someVar;
    }

    public function ListBox1Click($sender, $params)
    {
      $this->someVar = "XXXXXXXX";
      $this->Label8->Caption = $this->someVar;

    }

    public function ListBox2Click($sender, $params)
    {
      $this->Label8->Caption = $this->someVar;
    }
  }

  global $application;

  //Creates the form
  $Page1=new Page1($application);

  //Read from resource file
  $Page1->loadResource(__FILE__);

  //Shows the form
  $Page1->show();

?>

【讨论】:

  • 谢谢!它现在正在工作。我不知道,需要 $_SESSION !。并感谢代码 src!
猜你喜欢
  • 1970-01-01
  • 2022-01-28
  • 1970-01-01
  • 2016-09-15
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2012-09-28
相关资源
最近更新 更多