Bird
0
0

Given this class:

hard📝 Application Q15 of 15
PHP - Classes and Objects

Given this class:

class Book {
  public $title;
  public $author;
  public function __construct($title, $author) {
    $this->title = $title;
    $this->author = $author;
  }
}

// Create an array of books with titles and authors
$booksData = [
  ['1984', 'George Orwell'],
  ['Brave New World', 'Aldous Huxley'],
  ['Fahrenheit 451', 'Ray Bradbury']
];

// Fill this array with Book objects
$books = [];
foreach ($booksData as $data) {
  // Fill here
}

Which line correctly creates and adds a new Book object to $books inside the loop?

A$books[] = new Book($data[1], $data[0]);
B$books[] = new Book($data[0], $data[1]);
C$books[] = new Book($data);
D$books[] = Book($data[0], $data[1]);
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor parameters

    The constructor expects two parameters: title and author, in that order.
  2. Step 2: Match data array to constructor

    $data[0] is title, $data[1] is author, so new Book($data[0], $data[1]) is correct.
  3. Step 3: Add object to array

    Using $books[] = appends the new object to the array.
  4. Final Answer:

    $books[] = new Book($data[0], $data[1]); -> Option B
  5. Quick Check:

    Use new with correct params and append [OK]
Quick Trick: Match constructor params order exactly when using new [OK]
Common Mistakes:
  • Omitting new keyword
  • Passing whole array instead of separate params
  • Swapping title and author order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes