Trusted answers to developer questions

What are the naming conventions of variables in PHP?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

What is a variable?

A variable is a memory space or location that is meant to hold data. Variables are essential in programming because they are essentially the source of all operations a program code can perform.

If you wish to add two or more numbers, store a name and perform a retrieval. The outputs or inputs of this operation need to be placed somewhere in the computer’s memory.

Variables in PHP

In PHP, there are some governing rules to name and declare variables. However, doing this in PHP is quite easier than in languages like Java and C where you must also state the type of data to be stored.

It is widely known that PHP is a loosely typed language. This simply means that you don’t need to state the data type of the variable.

We’ll start by explaining the variable naming rules before discussing the variable naming conventions in PHP.

Variable naming rules PHP

Below are some rules that govern how to name your variables in PHP.

  • First, every variable must start with the special character .
  • Variables can then start with an underscore (_) or any letter, but not with a number or a special character.
  • The names of your variables cannot contain special characters such as &, %, #, or@.
  • Avoid using reserved keywords for your variable names, for example like, or, name, for, or while.
  • Variable names can contain underscores, numbers, and letters.

Examples

//right variable names

$manure = "growth supplements";
$_dressSize = 4;
$hymn123 = "my young days";


//wrong names

hey ="not so"; //doesn't have $
$123buckle ="still wrong"; //cannot follow $ with a number
$@gmail ="ooops error!"; //cannot use @

Variable naming conventions PHP

  • Names given to variables should make sense and relate to what it really stores. It is recommended to avoid one-letter names.
  • Also, try to use camel casecapitalizing the first letter of each following word for names with more than one word
  • Give your classes names that start with an uppercase letter.
//I wish to save my favorite quote

$myFavQoute = "live let's live";

//camelCased and reflects its data

RELATED TAGS

php
variables

CONTRIBUTOR

NDUKWE CHIDERA K.
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?