Home /PHP/Variables

Variables

This is PHP, and we want to be dynamic. What's more dynamic than a variable? Nothing. I know we are all still a little scared of variables from our crazy high school math teachers, but in reality, they are possibly your greatest asset in PHP. However, PHP variables have a few strict rules, which in my opinion is the best way to have them.

Variable Rules

  1. All variables must start with a $
  2. All variables must only contain alpha-numeric characters with the only exception of _ (an underscore)
  3. All variables must start with a lowercase letter or an underscore
  4. All variables are case sensitive, meaning that x and X are different variables

Unlike other languages, the syntax of creating a variable is remarkably simple. You don't have to put a type keyword in front of the variable name in order to declare it.

Example

<?php
    $myVar = "Greetings";
?>

You just created the variable $myVar with a value of the string "Greetings". PHP is smart enough to recognize what type of variable you are trying to define, well, kind of. We will get into more complex variables later. Let me show you how smart PHP is with variables really quick.

Example

<?php
    $myVar = "1";
    $myVar2 = true;
    echo $myVar;
    echo $myVar2;
?>

Result

11

Don't flip out. I know, I'll explain it in a second. First, we print out $myVar that gives us the integer 1. Next, we print out $myVar2, which returns the boolean true (1 is equivalent to true in the boolean type). Also, notice that after the echo, we didn't use quotations around our variable. With echo in PHP, you don't use quotations around the variables. You only use quotations to tell PHP that something is a string.

Variable Scope

Don't paint yourself in a corner. Understand scope before drafting your code full of variables.

Example

<?php
    $myVar = "Greetings";
    function sampleFunction()
    {
        $myVar = "No Greetings";
    }
    echo $myVar;
?>

Result

Greetings

I know you might not understand what a function is, but we will get to functions later. For now, just understand that the variables in a function are segregated from the rest of the code, unless you override it, which I will never show you how to do. It's terrible practice. Back to the example, why didn't it echo "No Greetings"? It is because the $myVar = "No Greetings"; is confined inside of the sampleFunction's scope. This may be a pain sometimes, but the scope is essential in writing solid code. We don't want variables overriding everything we type. So, just be smart when creating your variables. Think about where they need to be and what they are trying to accomplish.

Next: Operators