Today we’ll talk about variables in the PHP. Read below about what it is and how to work with it. Let’s start with the definition.
As in mathematics, x = 2 – the variable x is equal to two. Here x is the name of the variable, 2 is its value.
In PHP, variables start with a $ sign. For example: $x.
To assign a value to a variable, use the “=” sign, for example:
$x = 2;
This operation is called – assignment to a variable (or variable assignment).
Of course, the result of the whole expression can also be assigned to the variable. Example:
$sum = 5 + 10;
And then use it:
We can also use variables inside other expressions:
$x = 2 + 3; $y = ($x * 2) / ($x + 1); echo $y;
It is worth noting that variable names in PHP are case sensitive. That is, $x and $X are two different variables.
I would also like to say right away about variable naming. This is one of the most important skills of a good programmer, which beginners at first neglected. So, variables should always be given names that will clearly talk about what exactly is in this variable at the moment.
Examples of good names:
$subscriberEmail = ‘firstname.lastname@example.org’; $catName = ‘John’; $dayOfWeek = ‘Wednesday’;
Bad name example:
$result = $b ** 2 - 4 * a * c; // more appropriate name - $discriminant
In addition, there are certain rules that do not affect the performance of the code, but which all PHP programmers adhere to. This makes it easy to read the code of other programmers, and this is very important, since several people always work on large projects, and they must read each other’s code. I repeat, these rules are extremely important, because in the future, when you come to work, your code will be read and changed by other programmers, think about them now. So, we list these rules.
- The variable name should consist only of English words, and even more so only of the letters of the English alphabet. Not $imraKorta, much less $catname, strictly $catName.
- The variable name must begin with a lowercase letter, and the following words contained in its name must begin with a capital letter. This style is called camelCase. Not $catname or $CatName, only $catName.