【问题标题】:attempting to initialize php variables in constructor, getting error尝试在构造函数中初始化 php 变量,出现错误
【发布时间】:2012-05-26 09:44:35
【问题描述】:

我正在尝试在 php 构造函数方法中初始化类属性,但出现错误:

注意:未定义变量:C:\wamp\scaleUp\back\objects.php 第 9 行中的 _board

代码:

<?php
class Board {
public function __construct(){
    for ($x = 9; $x >= 0; $x--) {
        for ($y = 0; $y<10; $y++){
            $row = array();
            $row[$y] = $y;
        }
        $this->$_board = array(); 
            $this->$_board[$x] = $row;
    }
    echo "here";
    echo $this->$board[$x];
}       

 }

 $board =  new Board();

 ?>

【问题讨论】:

    标签: php class constructor


    【解决方案1】:

    访问对象字段的语法是$obj-&gt;field,而不是$obj-&gt;$field(除非您要访问存储在$field 中的字段名称)。

    【讨论】:

      【解决方案2】:

      这里,我已经为你调试好了代码。

      <?php
      class Board {
      public $_board;
      public function __construct(){
          for ($x = 9; $x >= 0; $x--) {
              for ($y = 0; $y<10; $y++){
                  $row = array();
                  $row[$y] = $y;
              }
              $this->_board = array(); 
                  $this->_board[$x] = $row;
          }
          echo "here";
          echo $this->_board[$x+1];/*OR*/print_r($this->_board[$x+1]);
          //$x had to be incremented here.
      }       
      
       }
      
       $board =  new Board();
      
       ?>
      

      正如其他人提到的,您必须遵循以下语法:$obj-&gt;property,而不是 $obj-&gt;$property

      【讨论】:

        【解决方案3】:

        _board 中删除$ -

        $this->_board = array();
        

        【讨论】:

          【解决方案4】:

          应该是

          $this-&gt;board

          您不需要第二个$ 符号。

          此外,在您的构造函数中,在内部循环中,您将在每次迭代中将 $row 重新初始化为数组。这是故意的吗?

          【讨论】:

            【解决方案5】:

            您必须将您的变量定义为成员变量 很烂

            class object {
             $_board ;
            ...
            ...
            ...
            }
            

            当你想使用它时,你必须使用以下语法

            $this->_board = .....;
            

            希望对你有帮助

            【讨论】:

              猜你喜欢
              • 2016-07-03
              • 2012-06-30
              • 1970-01-01
              • 2020-09-27
              • 2015-02-19
              • 1970-01-01
              • 1970-01-01
              • 2018-09-08
              • 2020-01-08
              相关资源
              最近更新 更多