Reputation: 845
I'm trying to initialize a class attribute within a php constructor method, but am getting the error:
Notice: Undefined variable: _board in C:\wamp\scaleUp\back\objects.php on line 9
code:
<?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();
?>
Upvotes: -1
Views: 2020
Reputation: 2960
Here, I have debugged the code for you.
<?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();
?>
As others mentioned, you have to follow the syntax: $obj->property
, not $obj->$property
.
Upvotes: 1
Reputation: 3922
You have to define your variable as a member variable suck as
class object {
$_board ;
...
...
...
}
and when you want to use it you have to use the following syntax
$this->_board = .....;
I hope this helps you
Upvotes: 0
Reputation: 42450
It should be
$this->board
You don't need the second $
sign.
Also, in your constructor, in the inner loop, you are re-initializing $row
as an array in every iteration. Is that intended?
Upvotes: 0
Reputation: 318748
The syntax to access an object field is $obj->field
, not $obj->$field
(unless you want to access the field name that is stored in $field
).
Upvotes: 2