0
0
PHPprogramming~15 mins

Class declaration syntax in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Class declaration syntax
📖 Scenario: You are creating a simple program to represent a car using a class in PHP. This will help you understand how to declare a class and create an object.
🎯 Goal: Build a PHP class called Car with a property and a method, then create an object and display its property.
📋 What You'll Learn
Declare a class named Car
Add a public property called color with the value red
Add a public method called getColor that returns the color property
Create an object of the Car class named myCar
Print the color of myCar using the getColor method
💡 Why This Matters
🌍 Real World
Classes help organize data and behavior together, like representing real things such as cars, users, or products in a program.
💼 Career
Understanding class declaration is essential for PHP developers to build organized, reusable, and maintainable code in web applications.
Progress0 / 4 steps
1
Declare the Car class with a color property
Write a PHP class declaration named Car with a public property called color set to the string "red".
PHP
Need a hint?

Use the class keyword followed by the class name Car. Inside, declare a public property $color and set it to "red".

2
Add a getColor method to the Car class
Inside the Car class, add a public method called getColor that returns the value of the color property.
PHP
Need a hint?

Define a public function named getColor inside the class. Use return $this->color; to return the property.

3
Create an object myCar of the Car class
After the Car class, create a new object named myCar using the new Car() syntax.
PHP
Need a hint?

Use $myCar = new Car(); to create an object from the class.

4
Print the color of myCar using getColor
Write a print statement that outputs the color of myCar by calling its getColor() method.
PHP
Need a hint?

Use print($myCar->getColor()); to show the color.