0
0
PHPprogramming~30 mins

Properties and visibility in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Properties and visibility
📖 Scenario: You are creating a simple PHP class to represent a Book in a library system. Each book has a title and an author. You want to control how these properties can be accessed and changed from outside the class.
🎯 Goal: Build a PHP class called Book with properties that have different visibility levels. Learn how to set and get these properties safely.
📋 What You'll Learn
Create a class named Book
Add a public property called title
Add a private property called author
Add a public method setAuthor to set the author property
Add a public method getAuthor to get the author property
Create an instance of Book and set the title and author
Print the title and author of the book
💡 Why This Matters
🌍 Real World
Controlling access to data inside objects is important in real-world software to protect sensitive information and keep code organized.
💼 Career
Understanding properties and visibility is a key skill for PHP developers working on web applications, APIs, and backend systems.
Progress0 / 4 steps
1
Create the Book class with a public title property
Create a class called Book with a public property named title and set it to an empty string.
PHP
Need a hint?

Use public string $title = ""; inside the class to create the property.

2
Add a private author property
Inside the Book class, add a private property called author and set it to an empty string.
PHP
Need a hint?

Use private string $author = ""; to keep the author hidden from outside.

3
Add public setter and getter methods for author
Add two public methods inside Book: setAuthor(string $name) to set the author property, and getAuthor() to return the author property.
PHP
Need a hint?

Use $this->author = $name; inside setAuthor and return $this->author; inside getAuthor.

4
Create a Book instance, set properties, and print them
Create a new Book object called $myBook. Set its title to "1984" and use setAuthor to set the author to "George Orwell". Then print the title and author in the format: Title: 1984, Author: George Orwell.
PHP
Need a hint?

Use $myBook->title = "1984"; and $myBook->setAuthor("George Orwell");. Then print with print("Title: {$myBook->title}, Author: {$myBook->getAuthor()}");.