Web Development /PHP Programming / Lesson
Web Development

Variables and Constants

Learn how PHP variables and constants store information, how to create and modify them, naming rules, scope, predefined constants, and best practices for managing data in PHP applications.

🎯

Learning Objectives

["Understand what variables are and why they are used in PHP.","Create PHP variables using the dollar sign syntax.","Understand PHP variable naming rules and conventions.","Store strings, numbers, booleans, arrays, and other values in variables.","Change the value stored in a variable.","Combine variables with strings and HTML output.","Understand the difference between variables and constants.","Create constants using define() and the const keyword.","Understand variable scope at a basic level.","Use meaningful names and good practices when working with variables and constants."]

📖

Lesson Content

Variables and Constants in PHP

Programs need a way to store information while they are running. A student management system may need to store a student’s name, course, registration number, and scores. An e-commerce application may need to store product names, prices, quantities, and customer information.

PHP uses variables and constants to store and work with values.

Understanding variables and constants is one of the most important foundations of PHP programming because almost every useful PHP application needs to work with data.

What Is a Variable?

A variable is a named location used by a program to store a value.

In PHP, variable names begin with the dollar sign $.

<?php

$name = "David";

?>

In this example, $name is the variable and “David” is the value stored in it.

The assignment operator = assigns the value on the right to the variable on the left.

Creating a Variable

A PHP variable can be created by assigning a value to a name.

<?php

$name = "John";
$age = 25;
$course = "PHP Programming";

?>

PHP determines the type of the value based on the value assigned to the variable.

Displaying Variables

The echo statement can be used to display the value stored in a variable.

<?php

$name = "John";

echo $name;

?>

The output is:

John

Variables can also be combined with text.

<?php

$name = "John";

echo "Welcome, ";
echo $name;

?>

This produces:

Welcome, John

Variables with Double-Quoted Strings

PHP allows variables to be embedded directly inside double-quoted strings.

<?php

$name = "John";

echo "Welcome, $name";

?>

The output is:

Welcome, John

This is known as variable interpolation.

Variable Assignment

The assignment operator is used to give a value to a variable.

<?php

$score = 75;

?>

The value of a variable can later be changed.

<?php

$score = 75;

$score = 90;

echo $score;

?>

The final output is:

90

This demonstrates that variables can change while a program is running.

Variables Can Store Different Types of Values

PHP variables can store many different types of values.

String

<?php

$name = "Dwallnet Technologies";

Integer

<?php

$age = 30;

Float

<?php

$price = 150000.50;

Boolean

<?php

$is_active = true;

Array

<?php

$courses = array(
	"PHP",
	"JavaScript",
	"Python"
);

The different PHP data types will be studied in more detail in the next lesson.

Variable Naming Rules

PHP variable names follow specific rules.

A variable name:

  • Must begin with a dollar sign.
  • Must begin with a letter or underscore after the dollar sign.
  • Can contain letters, numbers, and underscores.
  • Cannot contain spaces.
  • Is case-sensitive.

Valid examples include:

$name
$student_name
$age
$course1
$_total

Invalid examples include:

$student name
$1student
$student-name

Meaningful Variable Names

Variable names should clearly describe the information they contain.

For example:

$student_name = "David";
$student_age = 22;
$course_name = "PHP Programming";

These names are easier to understand than generic names such as:

$x = "David";
$y = 22;
$z = "PHP Programming";

Meaningful names make applications easier to read, debug, and maintain.

Case Sensitivity of Variables

PHP variable names are case-sensitive.

<?php

$name = "David";
$Name = "John";

echo $name;
echo $Name;

?>

$name and $Name are two different variables.

Developers should avoid unnecessarily creating variables whose names differ only by capitalization because this can make code confusing.

Changing Variable Values

A variable’s value can be changed by assigning a new value.

<?php

$status = "Pending";

$status = "Approved";

echo $status;

?>

The output is:

Approved

Using Variables in Calculations

Variables can be used in mathematical expressions.

<?php

$price = 5000;
$quantity = 3;

$total = $price * $quantity;

echo $total;

?>

The output is:

15000

This ability makes variables essential for applications involving calculations, prices, scores, statistics, and other numerical operations.

Variable Concatenation

PHP uses the dot . operator to concatenate strings.

<?php

$first_name = "John";
$last_name = "Doe";

$full_name = $first_name . " " . $last_name;

echo $full_name;

?>

The output is:

John Doe

Variables and HTML

PHP variables can be used to generate dynamic HTML content.

<?php

$name = "David";
$course = "PHP Programming";

?>

<h1>Welcome, <?php echo $name; ?></h1>
<p>You are studying <?php echo $course; ?>.</p>

This allows a single PHP template to display different information for different users.

What Is a Constant?

A constant is a name given to a value that is intended to remain unchanged during the execution of a program.

Unlike variables, constants are not normally changed after they have been defined.

Constants are useful for values such as:

  • Application names.
  • Company names.
  • Website URLs.
  • Configuration values.
  • Tax rates.
  • Version numbers.
  • Fixed application settings.

Creating Constants with define()

One way to create a constant is with the define() function.

<?php

define("SITE_NAME", "Dwallnet Technologies");

echo SITE_NAME;

?>

The constant is referenced without the dollar sign.

Constants Are Not Variables

Notice the difference between a variable and a constant:

<?php

$name = "David";

define("SITE_NAME", "Dwallnet Technologies");

echo $name;
echo SITE_NAME;

?>

The variable uses $name, while the constant uses SITE_NAME.

Creating Constants with const

PHP also supports the const keyword for declaring constants.

<?php

const APP_NAME = "Dwallnet LMS";

echo APP_NAME;

?>

The const keyword is commonly used when declaring constants in classes and at the appropriate scope in PHP applications.

Constant Naming Conventions

Constants are commonly written using uppercase letters with underscores separating words.

APP_NAME
SITE_URL
MAX_LOGIN_ATTEMPTS
DEFAULT_LANGUAGE

This convention makes constants easy to distinguish from ordinary variables.

Constants Cannot Be Changed Normally

A constant is designed to represent a fixed value.

<?php

define("SITE_NAME", "Dwallnet Technologies");

echo SITE_NAME;

The value should not be treated as something that changes during normal program execution.

Predefined PHP Constants

PHP provides several predefined constants that give developers useful information.

For example, PHP_VERSION contains the current PHP version.

<?php

echo PHP_VERSION;

?>

PHP also provides magic constants such as __FILE__ and __LINE__.

<?php

echo __FILE__;
echo __LINE__;

?>

These special constants can be useful for debugging and application development.

Variable Scope

Variable scope describes where a variable can be accessed within a PHP program.

At a basic level, variables can have different scopes depending on where they are created.

Local Variables

A variable created inside a function is generally local to that function.

<?php

function welcome() {

	$message = "Welcome to PHP";

	echo $message;
}

welcome();

?>

The variable $message exists within the function’s local scope.

Global Variables

A variable created outside a function is generally in the global scope.

<?php

$name = "David";

echo $name;

?>

Understanding scope becomes increasingly important when working with functions, classes, and larger PHP applications.

Global Keyword

PHP provides the global keyword for accessing certain global variables from within a function.

<?php

$name = "David";

function show_name() {

	global $name;

	echo $name;
}

show_name();

?>

Although this feature exists, developers should avoid unnecessary dependence on global variables because excessive global state can make applications harder to maintain.

Variable Variables

PHP has an advanced feature known as variable variables, where the value of one variable can be used as the name of another variable.

<?php

$name = "student";
$student = "David";

echo $$name;

?>

The output is:

David

This is an advanced feature and should be used carefully because it can make code harder to understand.

Checking Whether a Variable Exists

The isset() function can be used to determine whether a variable exists and is not null.

<?php

$name = "David";

if ( isset( $name ) ) {

	echo "The name variable exists.";

}

This is particularly useful when processing optional data or user input.

Removing Variables

The unset() function can remove a variable.

<?php

$name = "David";

unset( $name );

?>

After the variable has been unset, it should no longer be treated as an available variable in that scope.

Variable Naming Best Practices

Good variable naming makes PHP applications easier to understand.

Recommended practices include:

  • Use descriptive names.
  • Use consistent naming conventions.
  • Avoid unnecessary abbreviations.
  • Keep variable names focused on the data they represent.
  • Avoid using names that are difficult to understand.
  • Use lowercase names with underscores or another consistent project convention.

For example:

$student_name
$course_title
$total_score
$registration_number

Variables and Constants in a Practical Example

<?php

const SCHOOL_NAME = "Dwallnet Technologies";

$student_name = "David";
$course_name = "PHP Programming";
$course_duration = "3 Months";

echo "School: " . SCHOOL_NAME;
echo "<br>";
echo "Student: " . $student_name;
echo "<br>";
echo "Course: " . $course_name;
echo "<br>";
echo "Duration: " . $course_duration;

?>

In this example, SCHOOL_NAME represents a fixed application value, while the other values are stored in variables that could change from one student to another.

Practical Exercise

Create a PHP file called variables.php.

Your program should:

  1. Create a variable containing your name.
  2. Create a variable containing your age.
  3. Create a variable containing your course.
  4. Create a variable containing your school or organization.
  5. Create a constant containing the training center name.
  6. Display all the information on a webpage.
  7. Calculate and display a simple numerical result using two variables.

Summary

Variables allow PHP programs to store values that can change while the program runs. PHP variables begin with a dollar sign and can contain different types of data.

Constants represent values that are intended to remain fixed. They can be created using define() or const and are referenced without the dollar sign.

Understanding variable naming, assignment, concatenation, constants, scope, and basic variable management provides an important foundation for building PHP applications.

In the next lesson, we will study PHP data types and learn how PHP represents different kinds of information.

💻

Code Example

<?php

const SCHOOL_NAME = "Dwallnet Technologies";

$student_name = "David";
$course_name = "PHP Programming";
$score = 85;

echo "School: " . SCHOOL_NAME;
echo "<br>";
echo "Student: " . $student_name;
echo "<br>";
echo "Course: " . $course_name;
echo "<br>";
echo "Score: " . $score;

?>
⭐

Key Takeaways

["Variables store values that can change while a PHP program is running.","PHP variables begin with the dollar sign.","Variable names are case-sensitive.","Variables can store strings, numbers, booleans, arrays, and other values.","The assignment operator is used to assign values to variables.","The dot operator is used to concatenate strings.","Constants represent values that are intended to remain fixed.","Constants can be created using define() or const.","Constants are referenced without the dollar sign.","Meaningful variable and constant names improve code readability and maintainability."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress