0
0
PHPprogramming~15 mins

Readonly properties in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Readonly properties
📖 Scenario: Imagine you are creating a simple system to store information about books in a library. Each book has a title and an author. Once a book is created, its title and author should not change.
🎯 Goal: You will create a PHP class with readonly properties for title and author. Then, you will create an object of this class and display its properties.
📋 What You'll Learn
Create a class called Book with readonly properties title and author
Add a constructor to set the values of title and author
Create an object of the Book class with title '1984' and author 'George Orwell'
Print the title and author of the book
💡 Why This Matters
🌍 Real World
Readonly properties are useful when you want to store data that should not change after creation, like IDs, names, or fixed settings.
💼 Career
Understanding readonly properties helps you write safer and more reliable code, which is important in professional PHP development.
Progress0 / 4 steps
1
Create the Book class with readonly properties
Create a class called Book with two readonly public properties: title and author.
PHP
Need a hint?

Use the readonly keyword before the property type and name.

2
Add a constructor to set the readonly properties
Add a constructor method __construct to the Book class that takes two parameters: string $title and string $author. Inside the constructor, set the readonly properties $title and $author to the passed values.
PHP
Need a hint?

The constructor sets the readonly properties only once when the object is created.

3
Create a Book object with title and author
Create a variable called $book and assign it a new Book object with the title '1984' and author 'George Orwell'.
PHP
Need a hint?

Use the new keyword to create the object and pass the exact strings.

4
Print the book's title and author
Print the book's title and author using echo. Use the exact format: Title: 1984, Author: George Orwell.
PHP
Need a hint?

Use echo and access the properties with $book->title and $book->author.