php-variables-y-constantes-en-php

Variables and constants in PHP

  • 4 min

A variable is a named space where we store a value that can change during execution.

In any programming language, you need “containers” to store data. In PHP, these containers are variables and constants.

Although it may seem trivial, the way PHP handles these containers (and above all, from where you can see them) is unique. Understanding this now will save you hours of debugging in the future.

Variables: the dollar sign

In PHP, all variables start with the dollar sign $. No exceptions.

$name = "Luis";
$age = 35;
$price = 10.50;
$is_programmer = true;
Copied!

Naming conventions

Although PHP allows you to name your variables however you want (as long as they start with a letter or underscore), it’s advisable to apply a consistent convention:

  • Use camelCase for regular variables: $myFavoriteVariable.
  • The name should be descriptive (avoid $x, $y, $data).
  • Case Sensitive: $age and $Age are two different variables.

Where is the type?

PHP is a dynamically typed language. This means you don’t need to tell it “this is an integer” when creating the variable. PHP infers it from the value you assign.

$var = 10;      // Now it's an int
$var = "Hello"; // Now it's a string (PHP allows it!)
Copied!

Although PHP allows changing the type of a variable on the fly, in modern professional development we try to avoid it. If a variable is born as a number, it should die as a number to avoid chaos.

Scope

Here is where PHP behaves differently from JavaScript or C++. In PHP, variables have local scope to the function. This means there is a “wall” between what happens outside a function and what happens inside.

Look at this example:

$message = "Hello world"; // Global Variable

function greet() {
    // We try to use the global variable inside
    echo $message; 
}

greet();
Copied!

Result: Warning: Undefined variable $message.

Why? Because the greet() function is a sealed environment. It cannot “see” what is outside, unless we explicitly tell it to.

How to fix it?

The best practice, the one we will use 99% of the time, is to inject the data the function needs.

function greet($text) {
    echo $text;
}

greet($message); // "Hello world"
Copied!

We will cover this in depth later, but arrow functions or anonymous functions can capture external variables using use.

You could do this:

function greet() {
    global $message; // Import the variable from outside
    echo $message;
}
Copied!

Avoid using global. It makes your code unpredictable and hard to test. If a function needs data, pass it as an argument.

Constants: immutable values

Sometimes you need to store a value that should never change during the execution of the script: the database URL, the value of PI, or the path to your file folder.

For this, we use constants. Once defined, they cannot be redefined or deleted. And, unlike variables, they do not carry the $ sign.

We have two ways to define them. The classic battle: define vs const.

Option a: the define() function

This is the “old” or run-time way.

define('APP_NAME', 'My Great Application');

if (true) {
    define('STATUS', 'Active'); // Can be used inside an if
}
Copied!

Option b: the const keyword

This is the “modern” way and is processed at compile-time. It is faster and more readable.

const SPEED_OF_LIGHT = 299792458;
// const cannot be used directly inside an if/loop
Copied!

Which one should I use?

Use const whenever you can.

  1. It is more readable.
  2. It is the only way to define constants within Classes (OOP).
  3. It is slightly faster.

Reserve define() only for very rare cases where the constant name is generated dynamically.

Scope of constants

Constants declared outside a class are available inside functions within their namespace without using global. Keep in mind that namespaces are part of their name, so a constant MyApp\\VAT_RATE is not the same as a global constant VAT_RATE.

const VAT_RATE = 0.21;

function calculateTotal($price) {
    // VAT_RATE is visible here without issues
    return $price * (1 + VAT_RATE); 
}
Copied!