简体   繁体   中英

Why can't I access the value of a public variable in a PHP5 class from class functions?

I'm using CodeIgniter 2.0 with PHP5.3.2 on Apache 2.2.14 with MySQL 5.1.48-community. I created a small test controller to isolate another problem and discovered that my problem appears to be caused by public variable accessibility. Calling test1 or test2 will result in errors because they can't see the value of the array elements set in the other functions. Does anyone have any idea why this doesn't work? If so, what is the solution as I need to be able to access class-wide variables.

Thanks.

<?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: */

The error is in your code. When you __construct() the class, $this->data is equal to array() . An empty array. The only line that should work is the last one in your test1() function.

Remove all the echo statements from index() and test1() and try this:

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

This should work because now you have defined those array keys by running the function that defines them.

Try defining them in your __construct if you need access to them in every method of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM