簡體   English   中英

為什么我不能從類函數訪問PHP5類中的公共變量的值?

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

我在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: */

錯誤在您的代碼中。 當您對類進行__construct()$this->data等於array() 空數組。 唯一有效的行是test1()函數中的最后一行。

index()test1()刪除所有echo語句,然后嘗試以下操作:

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

這應該起作用,因為現在您已經通過運行定義它們的函數來定義了這些數組鍵

如果需要在類的每個方法中訪問它們,請嘗試在__construct定義它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM