0
0
PHPprogramming~15 mins

Constants in classes in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Constants in classes
📖 Scenario: Imagine you are creating a simple program to represent different types of vehicles. Each vehicle type has a fixed number of wheels that never changes. You want to store these fixed numbers as constants inside a class to keep your code organized and clear.
🎯 Goal: You will create a PHP class called Vehicle with constants for different vehicle types and their fixed number of wheels. Then, you will print out the number of wheels for a specific vehicle type using the class constant.
📋 What You'll Learn
Create a class named Vehicle.
Inside the class, define constants CAR_WHEELS with value 4 and MOTORCYCLE_WHEELS with value 2.
Outside the class, print the value of the constant CAR_WHEELS using the class name.
💡 Why This Matters
🌍 Real World
Constants in classes help keep fixed values organized and easy to maintain, like fixed settings or limits in a program.
💼 Career
Understanding class constants is important for writing clean, maintainable code in PHP, which is widely used in web development jobs.
Progress0 / 4 steps
1
Create the Vehicle class with constants
Create a class called Vehicle with two constants: CAR_WHEELS set to 4 and MOTORCYCLE_WHEELS set to 2.
PHP
Need a hint?

Use the const keyword inside the class to define constants.

2
Add a variable to hold the vehicle type
Create a variable called vehicleType and set it to the string 'CAR_WHEELS'.
PHP
Need a hint?

Use a simple variable assignment with the exact string 'CAR_WHEELS'.

3
Access the constant using the variable
Create a variable called wheels and set it to the value of the constant in Vehicle class using the variable vehicleType. Use Vehicle::${vehicleType} syntax.
PHP
Need a hint?

Use the constant() function to access a class constant dynamically.

4
Print the number of wheels
Print the value of the variable wheels using echo.
PHP
Need a hint?

Use echo $wheels; to display the number of wheels.