【问题标题】:Problem with class variables , to use them in if block in function类变量的问题,在函数的 if 块中使用它们
【发布时间】:2010-12-24 17:47:32
【问题描述】:

我在访问类中的变量时遇到问题,这是代码

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

谁能告诉我原因

【问题讨论】:

  • 如果你有另一个变量可以使用,你为什么要这样做?

标签: php class function


【解决方案1】:

我注意到的唯一明显的事情:

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

您将内部属性设置为未定义的变量 ($array),因此 $this->words 设置为 null。因此,下次您调用count($this->words) 时,它将返回0

其次 - 正如其他人所要求的 - 请在使用时发布整个代码

【讨论】:

    【解决方案2】:

    变量“$array”丢失。那么:

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

    也许这就是问题所在?

    问候

    【讨论】:

      【解决方案3】:

      我刚刚用构造函数和一些虚拟数据进行了一些重写,我复制了下面的源代码并使用构造函数来演示输出以及它使用类变量的事实。

      首先 $word 变量被定义为一个数组,我刚刚用两条数据填充它以证明它有效,然后构造函数调用$this-&gt;filterText("", "length") 输出 2 两次这是正确的,因为数组有两个字符串在里面。然后将 $word 数组重置为包含 5 个值,然后构造函数调用 $this-&gt;filterMinCount(0) 输出 5 这也是正确的。

      输出:

      22

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

      }

      【讨论】:

        猜你喜欢
        • 2021-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多