0
0
PHPprogramming~15 mins

Constructor promotion in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor Promotion in PHP
📖 Scenario: You are creating a simple PHP class to represent a book in a library system. Each book has a title, an author, and a number of pages.
🎯 Goal: Build a PHP class Book using constructor promotion to set the properties title, author, and pages. Then create an instance and display its details.
📋 What You'll Learn
Create a class called Book with three properties: title, author, and pages.
Use constructor promotion to initialize these properties in the constructor.
Create a variable called myBook that is an instance of Book with the title '1984', author 'George Orwell', and pages 328.
Print the book details in the format: 'Title: 1984, Author: George Orwell, Pages: 328'.
💡 Why This Matters
🌍 Real World
Constructor promotion helps write cleaner and shorter code when creating classes with many properties, common in real-world PHP applications like content management systems or APIs.
💼 Career
Understanding constructor promotion is useful for PHP developers to write modern, efficient, and readable code, which is valued in many web development jobs.
Progress0 / 4 steps
1
Create the Book class with promoted properties
Create a class called Book with a constructor that uses constructor promotion to declare and initialize the public properties title (string), author (string), and pages (int).
PHP
Need a hint?

Use the syntax public function __construct(public string $title, public string $author, public int $pages) {} inside the class.

2
Create an instance of the Book class
Create a variable called myBook and assign it a new Book object with the title '1984', author 'George Orwell', and pages 328.
PHP
Need a hint?

Use $myBook = new Book('1984', 'George Orwell', 328); to create the object.

3
Access the properties of the Book instance
Use a print statement to display the book details in the format: 'Title: 1984, Author: George Orwell, Pages: 328' by accessing the title, author, and pages properties of myBook.
PHP
Need a hint?

Use print("Title: {$myBook->title}, Author: {$myBook->author}, Pages: {$myBook->pages}"); to show the details.

4
Display the final output
Run the program and ensure it prints exactly: Title: 1984, Author: George Orwell, Pages: 328
PHP
Need a hint?

Make sure your print statement matches the exact output including punctuation and spacing.