Variables and Constants
A variable in PHP is used to store a value for us. We give the variable a name and it holds whatever information we assign to it, for example like a string of text, a number, an array, and much more. These named variables can then be used later on in our PHP code by simply referring to the variable's name.
Let's create a variable in PHP:
$apples = 5;
Variables in PHP begin with a dollar sign
$. By using the equal sign
=, we are not only declaring, or creating, a new variable, but now we are assigning that variable a value. In our example, the variable name is
$apple and we set its value to
5. Now when we echo our variable, we get this for the output:
Variable Naming Guidelines
As with every programming language, there are certain rules and guidelines for how you can name a variable in PHP, and they are as follows:
- Variables must begin with a dollar sign
- After the dollar sign
$, the first character must either be a letter or underscore
- After the first character, only alpha-numeric characters and underscores
_are allowed. This rules out spaces being used at all.
Examples of valid PHP variable names:
Examples of invalid PHP variable names:
Also keep in mind that variable names in PHP are case-sensitive. This means that
$Apple are different variables entirely.
A constant is like a normal variable in PHP in every way except that they store fixed-values instead of a value that can be changed whenever you want. Once you give a constant a value, that value cannot be changed moving forward. Because of this, constants are perfect for defining things that you know will never change and therefore you can safely use them in your scripts moving forward with confidence that the value hasn't be altered.
You can create constants by using the built-in
define() function that takes two parameters, the name of the constant and its value. After you define the constant, you can access it whenever you like as you would a normal variable.
Let's create our own constant:
// Defining a new constant
// Using the constant
echo('Thank you for visiting ');
Thank you for visiting https://sabe.io
First we echo
Thank you for visiting then the
URL constant. Together, the two echos displayed
Thank you for visiting https://sabe.io.
Constant names also follow the same guidelines and rules for variable names except that they don't need to start with a dollar sign
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js