【问题标题】:Why can't I access the value of a public variable in a PHP5 class from class functions?为什么我不能从类函数访问 PHP5 类中公共变量的值?
【发布时间】:2011-04-01 01:19:36
【问题描述】:

我在 Apache 2.2.14 和 MySQL 5.1.48-community 上使用 CodeIgniter 2.0 和 PHP5.3.2。我创建了一个小型测试控制器来隔离另一个问题,并发现我的问题似乎是由公共变量可访问性引起的。调用 test1 或 test2 将导致错误,因为它们无法看到在其他函数中设置的数组元素的值。有谁知道为什么这不起作用?如果是这样,解决方案是什么,因为我需要能够访问类范围的变量。

谢谢。

<?php
class Test extends CI_Controller
{
  public $data;

  function __construct()
  {
    parent::__construct();
    $this->data = array();
  }

  function index()
  {
    $this->data['test1'] = 'This is a test of class public variable access.<br />';         
    echo 'Class index() called.<br />';
    echo $this->data['test1'];  
  }

  function test1()
  {
    $this->data['test2'] = 'This is a second test of the class public variable access.<br />';          
    echo 'Class test1 called.<br />';
    echo $this->data['test1'];  
    echo $this->data['test2'];  
  }

  function test2()
  {
    echo 'The data array contains these two entries:<br />';
    echo $this->data['test1'];  
    echo $this->data['test2'];  
  }
}
/* End of file test.php*/
/* Location: */

【问题讨论】:

  • 这些调用方式和顺序以及输出是什么?
  • 错误信息的确切措辞是什么?
  • 看这段代码无法判断...需要CI_Controller,以及错误信息的详细信息。
  • 报错信息是:[code]A PHP Error was heard 严重性:Notice Message: Undefined index: test1 Filename: controllers/test.php Line Number: 26 [/code]
  • 我猜第 26 行在test1() 中?您是否总是在拨打test1() 之前先拨打index()?因为除非你这样做,否则索引 未定义。

标签: php oop codeigniter


【解决方案1】:

错误在您的代码中。当你 __construct() 类时,$this-&gt;data 等于 array()。一个空数组。唯一应该工作的行是test1() 函数中的最后一行。

index()test1() 中删除所有回显语句,然后试试这个:

  function test2()
  {
      $this->index();
      $this->test1();
      echo 'The data array contains these two entries:<br />';
      echo $this->data['test1'];  
      echo $this->data['test2'];  
    }

这应该可以工作,因为现在您已经通过运行定义它们的函数定义了这些数组键。

如果您需要在类的每个方法中访问它们,请尝试在 __construct 中定义它们。

【讨论】:

  • 问题,事实证明,是由于 CodeIgniter 每次调用函数时都会创建一个新的控制器对象实例,而不是正确地创建一个单例对象。因此,对不同函数的每次调用都在处理不同的对象和不同的数据,这意味着以前的函数存储的任何数据都不可用。
  • 我建议你回答你自己的问题并接受它,因为你是绝对正确的:)
  • @user 我不知道 CI 的细节,但通常每个请求只调用一个控制器操作。除非您在一个请求中显式调用多个方法,否则这不是单例对象的问题,而是请求之间的数据持久性问题(在 PHP 中不会像这样发生)。
猜你喜欢
  • 2017-07-09
  • 2017-04-15
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多