0
0
PHPprogramming~30 mins

Methods and $this keyword in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Methods and $this keyword
📖 Scenario: Imagine you are creating a simple program to manage a car's details. You want to store the car's brand and model, and then show this information using a method inside a class.
🎯 Goal: You will build a PHP class called Car with properties for brand and model. Then, you will add a method called displayInfo that uses the $this keyword to show the car's brand and model.
📋 What You'll Learn
Create a class named Car with two public properties: brand and model
Create an object of the Car class
Assign the values "Toyota" to brand and "Corolla" to model
Add a method called displayInfo inside the Car class that prints the brand and model using $this
Call the displayInfo method on the object and print the output
💡 Why This Matters
🌍 Real World
Classes and methods with <code>$this</code> are used to organize data and behavior in real-world PHP applications like websites and tools.
💼 Career
Understanding how to use classes and the <code>$this</code> keyword is essential for PHP developers building maintainable and reusable code.
Progress0 / 4 steps
1
Create the Car class with properties
Create a class called Car with two public properties: brand and model.
PHP
Need a hint?

Use class Car { } to create the class. Inside, declare public string $brand; and public string $model;.

2
Create a Car object and assign values
Create an object called $myCar from the Car class. Then assign "Toyota" to $myCar->brand and "Corolla" to $myCar->model.
PHP
Need a hint?

Create the object with $myCar = new Car();. Assign values using $myCar->brand = "Toyota"; and $myCar->model = "Corolla";.

3
Add displayInfo method using $this
Inside the Car class, add a public method called displayInfo that prints the car's brand and model using $this->brand and $this->model.
PHP
Need a hint?

Define the method with public function displayInfo() { }. Use echo "Brand: " . $this->brand . ", Model: " . $this->model; inside.

4
Call displayInfo method and print output
Call the displayInfo method on the $myCar object to print the car's brand and model.
PHP
Need a hint?

Call the method with $myCar->displayInfo(); to print the details.