0
0
PHPprogramming~15 mins

Constructor method in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Constructor method
📖 Scenario: You are creating a simple PHP class to represent a Book in a library system.
🎯 Goal: Build a PHP class called Book that uses a constructor method to set the book's title and author when creating a new Book object.
📋 What You'll Learn
Create a class named Book
Add a constructor method named __construct that accepts two parameters: $title and $author
Inside the constructor, assign the parameters to the class properties $title and $author
Create an object of the Book class with the title '1984' and author 'George Orwell'
Print the book's title and author in the format: Title: 1984, Author: George Orwell
💡 Why This Matters
🌍 Real World
Constructors are used in real-world PHP applications to set up objects with initial data, like user profiles, products, or articles.
💼 Career
Understanding constructors is essential for PHP developers to write clean, reusable, and organized code in web development jobs.
Progress0 / 4 steps
1
Create the Book class with properties
Create a PHP class called Book with two public properties: $title and $author.
PHP
Need a hint?

Use class Book { public $title; public $author; } to define the class and properties.

2
Add the constructor method
Inside the Book class, add a constructor method named __construct that takes two parameters: $title and $author. Assign these parameters to the class properties $this->title and $this->author.
PHP
Need a hint?

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

3
Create a Book object
Create a new object called $book from the Book class, passing '1984' as the title and 'George Orwell' as the author to the constructor.
PHP
Need a hint?

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

4
Print the book details
Print the book's title and author in this exact format: Title: 1984, Author: George Orwell using the $book object's properties.
PHP
Need a hint?

Use print("Title: {$book->title}, Author: {$book->author}"); to show the output.