views:

64

answers:

5

I am having problem in accessing variables in class here's the code

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);
         }
      }
}

Can any one tell me the reason

+1  A: 

I've tried the code, and it just works for me. Can you give the exact code as you test it?

Ikke
+1  A: 

write the exmple you use it it

moustafa
A: 

Only obvious thing I notice:

The line $this->words = $array; in Text::filterText() is wrong.

You are setting the internal attribute to an undefined variable ($array) so $this->words gets set to null. Thus, the next time you call count($this->words) it will return 0.

Secondly - as the other people have asked - please post the whole code as you use it.

catchdave
A: 

Variable "$array" is missing. Then:

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

Maybe this is the problem?

Regards

MiB
A: 

I've just done a bit of rewriting with a constructor and some dummy data, I've copied the source below and used the constructor to demonstrate the output and the fact that it is using class variables.

Firstly the $word variable is defined as an array and I’ve just populated it with two pieces of data to prove it works, the constructor then calls $this->filterText("", "length") which outputs 2 twice which is correct as the array has two strings in it. The $word array is then reset to contain 5 values and the constructor then calls $this->filterMinCount(0) which outputs 5 which is also correct.

Output :

22

5bingo5

Hope this helps

class Text {

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);
 }
}

}

Schkib