Sling Academy
Home/PHP/How to declare variables in PHP

How to declare variables in PHP

Last updated: January 09, 2024

Introduction

In PHP, variables are used to store data, such as numbers, strings, or more complex objects, that can be manipulated throughout your code. Let’s explore the syntax and rules for declaring variables in PHP.

Basics of Variables

In PHP, a variable starts with a $ symbol, followed by the name of the variable. A variable name must start with a letter or an underscore, followed by any number of letters, numbers, or underscores.

// Correct variable declarations
$variable1 = 'Hello, World!';
$Variable2 = 123;
$_variable3 = true;

// Incorrect variable declarations
$1variable = 'This will cause an error!';
$*varname = 'Invalid character!';

Naming Conventions

While PHP is a very flexible language when it comes to variable names, adopting naming conventions is crucial for writing clear and maintainable code. One common convention is ‘camelCase,’ where the first letter of each subsequent word is capitalized:

$myVariableName = 'PHP';

Other programmers prefer ‘snake_case’ where words are separated by underscores:

$my_variable_name = 'PHP';

Variable Types

PHP is a loosely typed language, which means that it does not require you to declare the type of variable explicitly. The type of the variable is determined dynamically based on the value it is assigned.

$stringVar = 'This is a string';
$intVar = 42;
$floatVar = 3.14;
$boolVar = false;
$arrayVar = array('PHP', 'Variables');

Scope of Variables

PHP variables can have different scopes. Variables declared outside of any function have a global scope and can only be accessed outside a function. To access a global variable inside a function, use the global keyword or the $GLOBALS array:

$globalVar = 'Accessible Everywhere!';

function test() {
  global $globalVar;
  echo $globalVar;
}

test(); // Outputs 'Accessible Everywhere!'

Static Variables

Normally, when a function completes, all of its variables are discarded. However, sometimes you want a local function variable to retain its value between calls. To do this, declare the variable as static:

function keepTrack() {
  static $count = 0;
  $count++;
  echo $count;
}

keepTrack(); // Outputs '1'
keepTrack(); // Outputs '2'

Variable Variables

In PHP, you can use variable variables – that is, variables whose names are dynamically set and used. It can be done by using a double $ before the variable name:

$varName = 'dynamic';
$varName = 'PHP';

echo $dynamic; // Outputs 'PHP'

References

PHP also allows the use of references, which means two variable names point to the same content.

$originalVar = 'PHP 8';
$referenceVar = &$originalVar;

echo $referenceVar; // Outputs 'PHP 8'
$referenceVar = 'PHP 7';
echo $originalVar; // Outputs 'PHP 7'

Conclusion

Declaring variables in PHP is simple yet flexible. By understanding and using the concepts of scope, static, and reference variables correctly, along with clean naming conventions, you can write more efficient and readable PHP scripts.

Next Article: How to define constants in PHP

Previous Article: 3 Ways to Make Comments in PHP: Best Practices for Readable Code

Series: Basic PHP Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array