Beginner php PHP 15 min read

Variables

Variables

Understanding Comments in PHP

When writing code, it's essential to include notes to yourself and other developers. These are called comments, and PHP offers different ways to add them. A simple, single-line comment begins with //. Anything following this marker on the same line is ignored by the PHP interpreter. For instance, print 2 + 2; // This is a comment will output 4, but the comment itself won't be executed.

For longer explanations or sections of code you want to temporarily disable, you can use multi-line comments. These begin with / and end with /. Everything between these markers is also ignored.

/*
This is a multi-line comment.
It can span several lines of code.
This is useful for temporarily disabling a block of code.
*/

While you might occasionally encounter older code using shell-style comments (starting with #), the // syntax is the preferred and most common way to write single-line comments in modern PHP development.

Introducing Variables: Dynamic Data in PHP

One of the key characteristics of computer programs is their ability to adapt and change based on the data they process. This dynamism is largely enabled by variables. A variable is essentially a named storage location within your code that holds a value. Think of it as a container labeled with a meaningful name.

The term "variable" is apt because the value stored within it isn’t fixed; it can change during a program's execution, and even between different runs.

For example, a variable could track the current date and time, and a program might use this value to display a personalized greeting on a user's birthday. Another variable could represent the size of a log file, and your code could automatically back up the contents and create a new file when the log reaches a certain size.

Beyond just changing between program executions, variables are frequently updated during a program's runtime. Consider an online shopping cart; a variable would track the total value, increasing as items are added and decreasing when items are removed. Similarly, a variable might represent the number of users currently logged into a system, dynamically adjusting as users join or leave. A high value for this variable might even trigger an automated process to allocate more system resources.

Declaring and Assigning Variables

In PHP, a variable acts as a named container that holds a piece of data. To create a variable, you give it a name and then assign a value to it. Here's a basic example:

$age = 21;

A crucial characteristic of PHP variables is that they must begin with a dollar sign ($). This distinguishes them from keywords and identifiers used in other programming languages.

The assignment process uses the equal sign (=). In this context, = is the assignment operator. The variable's name appears on the left side of the equal sign, and the value you want to store goes on the right. Like most PHP statements, the entire assignment is terminated with a semicolon.

Expressions and Values

The part of the code appearing after the assignment operator is called an expression. An expression is essentially something that produces a single value. The simplest type of expression is a literal – a direct representation of a value, such as the number 21, the floating-point number 3.5, the boolean value true, or the text string "Matt Smith".

However, expressions can be much more complex. They might involve calculations, incorporate other variables, or even call functions (which we's explore more fully later). When a complex expression is used, PHP evaluates it first – that is, it determines the resulting value – before assigning that value to the variable.

Here are some examples:

$username = "matt";            // Assigning a string literal
$total = 3 + 5;                // A calculated value
$numSlices = $numPizzas * 8;   // A calculation using another variable
$timestamp = time();           // Calling a function to get a value

In the first example, the string "matt" is directly assigned to the $username variable. The $total variable holds the result of 3 + 5, which is 8. The $numSlices variable’s value depends on the value of another variable, $numPizzas. Finally, the $timestamp variable receives the value returned by the time() function.

Variable Initialization and Errors

If you attempt to run the code above without first assigning a value to $numPizzas, PHP will issue a warning. For instance:

PHP Warning: Undefined variable $numPizzas in main.php on line 4

This warning indicates that $numPizzas is undefined – it hasn't been given an initial value. It’s essential to always assign a value to a variable before you try to use it in a calculation or expression. This practice is known as variable initialization. We'll delve into the different data types variables can hold in the next section.

Utilizing Variable Values

Once you've defined a variable in your PHP code, you can use its name wherever you need to access the data it holds. Let's illustrate this with a practical example: calculating the total number of pizza slices. Create a file named pizza.php and paste the following code into it.

<?php
$numPizzas = 1;
$numSlices = $numPizzas * 8;
print $numSlices;
print "\n";
$numPizzas = 3;
$numSlices = $numPizzas * 8;
print $numSlices;
print "\n";
?>

In this example, we initially assign the value 1 to the variable $numPizzas. We then compute the number of slices by multiplying $numPizzas by 8 and storing the result in the $numSlices variable. The print statement displays the value held within $numSlices, and \n inserts a newline character, moving the cursor to the next line for subsequent output.

A key characteristic of variables is their ability to change during program execution. Following the initial calculation, we modify the value of $numPizzas from 1 to 3. The $numSlices variable is then recalculated based on this updated value of $numPizzas, and the new result is displayed. Running this script from the command line produces the following output:

% php pizza.php

Observe how the value of $numSlices changes from 8 to 24 as the program progresses. This demonstrates how variable values are dynamically calculated and updated based on changes within the program. Experiment by altering the initial value assigned to $numPizzas to see how it affects the final number of slices.

Variable Naming Conventions

PHP enforces specific rules and established practices for naming variables. The most important rule is that all variable names must begin with a dollar sign ($). Forgetting this crucial dollar sign when referencing a variable will typically result in a fatal error – a serious error that halts the program. We're going to cover constants in the next section, which are similar but have different rules.

Following the dollar sign, the subsequent character must be a letter (a-z, A-Z) or, in some cases, an underscore (_). While underscores are allowed, it's common practice to start variable names with a letter for better readability.

Introducing PHP Variables: Your Data Containers

In PHP, variables are fundamental – they act as labeled containers that hold data your program will work with. Think of them as named boxes where you can store values like text, numbers, or more complex information.

Naming Your Variables: Rules and Conventions

When creating a variable, you need to give it a name. PHP has specific rules about what characters are allowed in a variable name. They must begin with a letter or underscore (_). After the first character, you can use letters, numbers, or underscores. For example, $myVariable, $_count, and $user123 are all valid. However, names like $1stUser are not allowed because they begin with a number.

A crucial point: PHP variable names are not case-sensitive for many language elements, but they are case-sensitive for variables themselves. This means $myVar and $MyVar are treated as completely different variables.

To ensure readability and maintainability, developers often adhere to established naming conventions:

  • Lowercase: Single-word variable names are typically written entirely in lowercase, such as $userName or $total.
  • Snake Case: For multi-word variables, snake case is a popular choice. This involves writing everything in lowercase and separating words with underscores, like $gameLivesRemaining or $customerNumber.
  • Lower Camel Case: Another common style is lower camel case, where the first word is lowercase and subsequent words begin with a capital letter, such as $gameLivesRemaining or $customerNumber.

Regardless of the style you choose, consistency is key. The most important consideration is that the name clearly indicates what data the variable holds. Avoid cryptic abbreviations like $custNo or generic names like $x – opt for descriptive names that enhance understanding.

<?php
$username = "matt";
print $userName;
?>

The code above demonstrates the importance of case sensitivity. Although $username is assigned a value, the code attempts to print $userName, which hasn't been defined. This results in a PHP warning message: "Undefined variable $userName". It's the same as trying to use a variable that hasn't been assigned a value in the first place.

Case Sensitivity vs. Case Insensitivity

It's important to note that while variable names are case-sensitive, other parts of PHP are case-insensitive. This includes keywords like if, for, and print, data types like int and string, and values like true and false. While PHP doesn’t require it, it’s a widely accepted practice to use lowercase for keywords and data types, and lower camel case for function and method names, to promote code clarity.

The exercises at the end of this lesson will provide further guidance on coding styles and best practices.