尝试在构造函数中初始化 PHP 变量,出现错误


attempting to initialize php variables in constructor, getting error

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

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

法典:

<?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();
 ?>

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

在这里,我已经为您调试了代码。

<?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->property,而不是$obj->$property

_board中删除$ -

$this->_board = array();

它应该是

$this->board

您不需要第二个$符号。

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

你必须将变量定义为成员变量吸吮为

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

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

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

我希望这对你有帮助