-1

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

 ?>
1

5 Answers 5

2

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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

remove the $ from _board -

$this->_board = array();

Comments

0

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?

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.