2009-12-09 67 views
0
我有在这里上课变量的访问问题

块是代码问题与类变量,使用它们,如果在功能

class Text { 

     private $text = ''; 

     private $words = ''; 
     // function to initialise $words 
     private function filterText($value,$type) { 
      $words = $this->words; 
      echo count($words); // works returns a integer 
      if($type == 'length') { 
       echo count($words); // not works returns 0 
      } 
      $this->words = $array; 
     } 
     // even this fails 
     public function filterMinCount($count) { 
     $words = $this->words; 
     echo count($words); 
     if(true){ 
      echo 'bingo'.count($words); 
     } 
     } 
} 

任何一个可以告诉我原因

+0

你为什么这样做,无论如何,如果你有其他变量,您可以使用? – yoda 2009-12-09 07:44:33

+2

笏是标点符号 – 2009-12-09 07:50:17

回答

0

唯一明显的事情我注意:

线$this->words = $array;Text::filterText()是错误的。

您正在将内部属性设置为未定义变量($array),所以$this->words设置为null。因此,下次你打电话时count($this->words)将返回0

其次 - 正如其他人问 - 请发布整个代码,因为你使用它

0

变量 “$阵” 不见了。然后:

<?php 
    echo count(''); // 1 
    echo count(null); // 0 
?> 

也许这是什么问题?

问候

0

我只是做了一些有一个构造函数和一些虚拟数据重写的,我已经复制下面的来源和使用的构造函数来演示输出,它使用类变量的事实。

首先在$字变量定义为一个数组,我只是填充它有两个数据来证明它的工作原理,然后构造函数调用$this->filterText("", "length"),输出2这是正确的,因为数组有两个字符串两次它。的$字阵列然后复位为包含5个值,然后将构造函数调用$this->filterMinCount(0),输出5,它也是正确的。

输出:

5bingo5

希望这有助于

类文本 {

private $text = ''; 

private $words = array('1', '2'); 

function __construct() 
{ 
    //calling this function outputs 2, as this is the size of the array 
    $this->filterText("", "length"); 

    echo "<br />"; 

    $this->filterMinCount(0); 
} 

// function to initialise $words 
private function filterText($value,$type) 
{ 
    $words = $this->words; 

    echo count($words); // works returns a integer 

    if($type == 'length') 
    { 
     echo count($words); // not works returns 0 
    } 

    //reset the array 
    $this->words = array(1,2,3,4,5); 
} 

// even this fails 
public function filterMinCount($count) 
{ 
    $words = $this->words; 

    echo count($words); 

    if(true) 
    { 
     echo 'bingo'.count($words); 
    } 
} 

}