1

I searched many solutions here on Stackflow but i dont get it fixed. Its simple i have a class Library and i want to store Books object there and display them. My code is simple but i dont get it. I am getting this ERROR: Undefined variable: books

        class Library{

             var $books = array();

            function addBook($bok){
                $books[] = $bok;
            }

            function displayBooks(){
                foreach($books as $b){
                    $b->display();
                }
            }
        }

        class Book{
            var $title;
            function __construct($name){
                $this->title = $name;
            }

            function display(){
                echo $this->title;
            }
        }


        $lib = new Library();
        $lib->addBook(new Book("Test Title"));
        $lib->displayBooks();
3
  • 5
    from inside the class, the variable should be referred to as $this->books and not $books Commented Sep 19, 2017 at 13:10
  • Also, please note, that var not recommended since release of PHP 5.0 (that was in 2006 or so) ... you might need to get a newer tutorial/book. Commented Sep 19, 2017 at 13:17
  • what you mean? i cant dont write var ist part of the syntax i tested it? what i schould use instead? Commented Sep 19, 2017 at 13:18

2 Answers 2

2

$books is your instance variable of Library, but to access it you should write $this->books, not $books. (As Calimero commented under the question)

Also, it's a good practice to always make explicit use of the visibility (public, private, protected).

Example:

class Library {
  private $books = [];
  public function addBook($book){
    $this->books[] = $book;
  }

  public function displayBooks(){
    foreach($this->books as $b){
      $b->display();
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Need to reference your class array with $this. Example below.

function addBook($book) {
    $this->books[] = $book;
}

function displayBooks() {
    foreach($this->books as $book){
        $book->display();
    }
}

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.