Variables. You probably remember them from Algebra. Assuming you took algebra back in high school. Surely you remember:
Where x is an unknown variable which variable you had to solve for. Variables are items that are used to assign and store values.
Fortunately in PHP, you don’t have to solve for any unknown values. This time YOU will know what value is assigned to your variables. Variables in PHP can be viewed as “storage containers” if you will. You can store numbers, text, paragraphs, and in some cases even commands.
So what does a PHP variable look like?
Variables in PHP always start with a dollar sign. The above example is just a variable without any value assigned to it. So how to we assign a value to a variable?
$container = 5;
So what, you assigned a number to a variable, I still don’t understand how this is used.
Variables reusable throughout your code. Let’s say you assigned a little more than just a number to a variable:
$container = ‘Knight Rider, A shadowy flight into the dangerous world of a man who does not exist. Michael Knight, a young loner on a crusade to champion the cause of the innocent, the helpless, the powerless, in the world of criminals who operate above the law…’;
Let’s say you were working on a web page that required the opening narration of Knight Rider to be repeated throughout the site, do you really want to type all that out each and every time? Or would you rather store all that in a one word variable? It might just be me, but I think it’s a tad bit easier to type out “$container“.
There are rules to naming variables, and here’s how not to name them:
$5 = 5; //This is invalid, variable can’t be numbers nor start with numbers.
$_container = ‘How about this?’; //Also invalid. Variables may not start with an underscore.
$über_container = ‘And this?’; //Invalid. Variables may not start with special characters.
$plastic container = ‘nope’; //Variables may not contain spaces.
So how may I name them?
We’ll get in to that down the road.
I recommend you name your variables terms you can easily follow and terms that are relatable to the values you will assign to them.
Now that you know a little more about how variables work, you are probably asking yourself in which context are variables used. Keep reading to find out.