0

I have a nested PHP class which I can access by

public function getbookname($bookno){
  $namex='No book';
  switch($bookno){
     case 1:
        $namex=$this->book1->bookname;
        break;
     case 2:
        $namex=$this->book2->bookname;
        break;
     case 3:
        $namex=$this->book3->bookname;
        break;
  }
  return $namex;
}

The class may have up to 50 or so books so I need to create the "bookX" dynamically. I searched and found how to create variable names dynamically.

So I did this

public function getbookname($bookno){
  return ${'$this->book' . $bookno. '->bookname'};
}

But it does not work, I get the following error:

Notice: Undefined variable: $this->book1->bookname in 
C:\wamp\www\htdocs\lib4\includes\oop_book.php on line 32

As you can see $this->book1->bookname is a correct method call.

I also tried

public function getbookname($bookno){
  $methodreturn = ${'$this->book' . $bookno. '->bookname'};
  return $methodreturn;
}

With the same result. Please help.

Community
  • 1
  • 1

4 Answers4

1

Try it like this:

public function getbookname($bookno){
  $methodName = 'book' . $bookno;
  return $this->$methodName->bookname;
}
RnatMigL
  • 21
  • 1
  • 2
1

Something like this should suffice.

$this->{'book'. $bookno}->bookname;

Have a read of variable variables on the manual.

For example;

<?php

class books {

  private $book1 = "Harry Potter";
  private $book2 = "Dracula";
  private $book3 = "The Dictionary";

  public function getBook($bookno) {
     return $this->{'book'. $bookno};
  }
}

$books = new books();

echo $books->getBook(2); //Output: Dracula
ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
1

You should restructure your Code and use Arrays instead!

Like:

   class x {
     private $books = array();

     public function addBook($book) {
        $this->books[] = $book;
     }
     public function getBookName($no) {
        return $this->books[$no]->bookname;
     }
   }
0

try something like this

public function getbookname($bookno){
  return $this->$bookno->bookname;
}
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40