开发者

Problem with class variables , to use them in if block in function

开发者 https://www.devze.com 2022-12-13 18:34 出处:网络
I am having problem in accessing variables in class here\'s the code class Text { private $text = \'\';

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 reaso开发者_JAVA百科n


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.


Variable "$array" is missing. Then:

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

Maybe this is the problem?

Regards


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

}

0

精彩评论

暂无评论...
验证码 换一张
取 消