Categories

Articles in Basics Category

PHP Variables and Constants

In programming, a variable is a value holder. A variable can hold the same value or the value it holds can get changed during the runtime of a program.

<?php

$greeting = 'Welcome';

$name = 'Tom';
echo "$greeting $name";
echo '<br />';

$name = 'Jack';
echo "$greeting $name";
echo '<br />';

$name = 'Edward';
echo "$greeting $name";
echo '<br />';

?>

Run above script in a web browser and you would see following three lines.

Welcome Tom
Welcome Jack
Welcome Edward

In this script both $greeting and $name are variables. You can see that $greeting holds the same value throughout the script while value of $name gets changed. <br /> tags are for having line breaks in the web browser.

Naming Variables

In PHP, all variables should start with $ sign. The part after $ sign is called variable name.

  • Variable names can only contain letters, numbers and underscores.
  • A variable name should only start with a letter or an underscore.
  • Variable names are case-sensitive. That means $Greeting and $greeting are two different variables.

Refer PHP Coding Standards to see some good practices in variable naming.

$firstName // Correct
$first_name // Correct
$firstName1 // Correct
$_firstName // Correct
$first-name // Wrong (Hyphen is not allowed)
$4firstName // Wrong (Starts with a number)

Arrays

All the variables considered so far could contain only one value at a time. Arrays provide a way to store a set of values under one variable. Refer the article Arrays to learn more about arrays in PHP.

Predefined Variables

PHP provides a set of predefined variables. Most of them are arrays. Their availability and values are based on the context. For an example $_POST contains all the values submitted via a web form that used post method. Refer PHP manual for more information on predefined variables.

Constants

As name describes, constants hold values that don’t get changed during the runtime of a script. Same naming rules apply for constants except that $ sign is not used when defining constants. To give an emphasis to constants, it’s a common practice to define constant names in upper-case.

define('SITE_URL', 'http://www.example.com');
echo SITE_URL; // Would print http://www.example.com

Once defined, a new value cannot be assigned to a constant.

define('SITE_URL', 'http://www.google.com');
echo SITE_URL; // Would still print http://www.example.com
Where to Head from Here...