PHP Constants and Magic Constants Practice Questions with Solutions

Introduction

In PHP, constants are used to store values that should not change during normal program execution. For example, you can define constants for a company name, tax rate, website URL, or application settings.

PHP also provides magic constants, which automatically return information about the code, such as the current file name, line number, directory, or class name.

In this chapter, you will learn constants and magic constants through solved practice questions with PHP code, sample output, and beginner-friendly explanations. PHP Constants and Magic Constants Practice Questions with Solutions to help you understand the concepts.

Question 1: Create a Constant Using define()

Problem Statement: Create a constant named SITE_NAME and display the website name.

PHP Solution


<?php
define("SITE_NAME", "CoderMantra");

echo SITE_NAME;
?>

Sample Output

CoderMantra

Explanation

  • define() creates a named constant.
  • SITE_NAME is the constant name.
  • "CoderMantra" is its value.
  • echo displays the constant’s value.

Unlike a normal variable, a constant is accessed without the $ symbol.

Question 2: Create Constants Using const

Problem Statement: Create constants for a company name and its establishment year. Display both values.

PHP Solution


<?php
const COMPANY_NAME = "VSIT Coding Institute";
const ESTABLISHED_YEAR = 2008;

echo "Company: " . COMPANY_NAME . "<br>";
echo "Established: " . ESTABLISHED_YEAR;
?>

Sample Output

Company: VSIT Coding Institute

Established: 2008

Explanation

The const keyword declares a constant.

PHP constants are commonly written in uppercase with underscores separating words, although uppercase naming is a convention rather than a requirement.

At the top level, const declarations are evaluated at compile time. The define() function is useful when a constant needs to be created conditionally during execution.

Question 3: Calculate Using Constants

Problem Statement: Create constants for a product’s price and quantity. Calculate and display the total cost.

PHP Solution


<?php
const PRODUCT_PRICE = 500;
const PRODUCT_QUANTITY = 4;

$totalCost = PRODUCT_PRICE * PRODUCT_QUANTITY;

echo "Product Price: Rs. " . PRODUCT_PRICE . "<br>";
echo "Quantity: " . PRODUCT_QUANTITY . "<br>";
echo "Total Cost: Rs. " . $totalCost;
?>

Sample Output

Product Price: Rs. 500

Quantity: 4

Total Cost: Rs. 2000

Explanation

Constants can be used in mathematical calculations just like values stored in variables.

Here, PRODUCT_PRICE is multiplied by PRODUCT_QUANTITY. The result is stored in the variable $totalCost.

The product details remain fixed unless the program’s constant definitions are changed.

Question 4: Calculate GST Using Constants

Problem Statement: A product costs ₹2,000 before tax. Create constants for the price and a sample GST rate of 18%. Calculate the GST amount and final price.

PHP Solution


<?php
const PRODUCT_PRICE = 2000;
const GST_RATE = 18;

$gstAmount = PRODUCT_PRICE * GST_RATE / 100;
$finalPrice = PRODUCT_PRICE + $gstAmount;

echo "Product Price: Rs. " . PRODUCT_PRICE . "<br>";
echo "GST Amount: Rs. " . $gstAmount . "<br>";
echo "Final Price: Rs. " . $finalPrice;
?>

Sample Output

Product Price: Rs. 2000

GST Amount: Rs. 360

Final Price: Rs. 2360

Explanation

The program calculates the tax using:

  • GST amount = product price × GST rate ÷ 100
  • Final price = product price + GST amount

The 18% rate is used only as an example. Actual GST rates depend on the product or service and applicable tax rules.

Question 5: Check Whether a Constant Exists

Problem Statement: Create a constant named APP_NAME. Use defined() to check whether the constant exists before displaying its value.

PHP Solution


<?php
define("APP_NAME", "Student Management System");

if (defined("APP_NAME")) {
    echo "Application: " . APP_NAME;
} else {
    echo "Application constant is not defined.";
}
?>

Sample Output

Application: Student Management System

Explanation

The defined() function checks whether a constant has been defined.

It returns true if the constant exists and false otherwise. This is useful when working with optional configuration values.

Question 6: Display the Current File Name Using __FILE__

Problem Statement: Write a PHP program that displays the full path of the current PHP file.

PHP Solution


<?php
echo __FILE__;
?>

Sample Output

C:\xampp\htdocs\php_practice\question6.php

Example output for a Windows XAMPP installation. Your actual path will be different.

Explanation

__FILE__ is a magic constant that returns the full path and filename of the current file.

Its value is determined automatically by PHP. You do not need to define it yourself.

This can be useful when debugging file locations or including files from specific directories.

Question 7: Display the Current Directory Using __DIR__

Problem Statement: Display the directory containing the current PHP file.

PHP Solution


<?php
echo __DIR__;
?>

Sample Output

C:\xampp\htdocs\php_practice

Example output. The actual directory depends on where you save the file.

Explanation

__DIR__ returns the directory path of the current file, without the filename.

It is commonly used to build reliable paths when including other PHP files.

For example:

require __DIR__ . "/config.php";

This references config.php in the same directory as the current file.

Question 8: Display the Current Line Number Using __LINE__

Problem Statement: Display the line number on which the magic constant __LINE__ appears.

PHP Solution


<?php
echo "Checking PHP line number.<br>";
echo __LINE__;
?>

Sample Output

Checking PHP line number.

3

Explanation

__LINE__ returns the current line number in the PHP source file.

In this example, the second echo statement is on line 3. If you move the statement to another line, the output will change accordingly.

This magic constant can help when debugging code.

Question 9: Display the Class Name Using __CLASS__

Problem Statement: Create a class named Student and display its class name using __CLASS__.

PHP Solution


<?php
class Student
{
    public function showClassName()
    {
        echo __CLASS__;
    }
}

$student = new Student();
$student->showClassName();
?>

Sample Output

Student

Explanation

__CLASS__ returns the name of the class in which it is written.

Here, the magic constant is inside the Student class, so it displays Student.

You will explore classes and objects in more detail in the object-oriented PHP chapters.

Question 10: Create a Website Configuration Using PHP Constants and Magic Constants

Problem Statement: Create a small website configuration that stores the site name and version, then displays the site information, current filename, and directory.

PHP Solution


<?php
define("SITE_NAME", "CoderMantra");
const SITE_VERSION = "1.0";

echo "<h2>Website Configuration</h2>";
echo "Site Name: " . SITE_NAME . "<br>";
echo "Version: " . SITE_VERSION . "<br>";
echo "File Name: " . basename(__FILE__) . "<br>";
echo "Directory: " . __DIR__;
?>

Sample Output

Website Configuration

Site Name: CoderMantra

Version: 1.0

File Name: question10.php

Directory: C:\xampp\htdocs\php_practice

The filename and directory shown are examples. Your output depends on where you save the file.

Explanation

This program combines regular constants and a magic constant:

  • SITE_NAME stores the website name.
  • SITE_VERSION stores the version number.
  • __FILE__ provides the current file’s full path.
  • basename(__FILE__) extracts just the filename.
  • __DIR__ provides the current directory.

This is a basic example of application configuration. Larger applications often keep configuration in separate files or environment variables.

Key Takeaways

  • Constants store values that should not be reassigned during normal program execution.
  • Use define() or const to declare constants.
  • Access constants without the $ symbol.
  • defined() checks whether a constant exists.
  • __FILE__ returns the current file’s full path.
  • __DIR__ returns the current directory.
  • __LINE__ returns the source line number.
  • __CLASS__ returns the current class name in class context.
  • Magic constants are built into PHP and do not need to be declared.
  • Constants are useful for application settings, fixed values, and configuration.

Frequently Asked Questions

1. What is a constant in PHP?

A constant is a named value that cannot be reassigned after it has been defined.

2. What is the difference between a variable and a constant?

Variables begin with $ and can be reassigned. Constants do not use $ and cannot be reassigned after definition.

3. What is the difference between define() and const?

Both create constants. define() creates a constant at runtime, while const declares a constant at compile time. They have different restrictions on where and how they can be declared.

4. Are PHP constants case-sensitive?

Constants created with define() are case-sensitive by default. Constants declared with const are also case-sensitive.

5. What does __FILE__ return?

It returns the full path and filename of the current PHP file.

6. What is the difference between __FILE__ and __DIR__?

__FILE__ includes the filename, while __DIR__ returns only the directory containing the file.

7. What is __LINE__ used for?

It returns the current source-code line number and can be helpful when debugging.

8. What does __CLASS__ do?

It returns the class name in which it is used. It is especially useful when debugging object-oriented PHP code.

9. Can a constant contain an array?

Yes. PHP supports array constants using define() or const, subject to PHP’s constant-expression rules.

10. Can I change a constant after defining it?

No. You cannot reassign a defined constant. If a value needs to change during program execution, use a variable instead.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top