This tutorial will guide you understanding variable in PHP
In day to day programming, we’ll almost need to store a value at any kind of data type such as integer, string, array, etc…
PHP provides two places to store that values that are in a (1) variable or (2) constant. In another tutorial we have discussed the constant, now we will look depth about variable in PHP.
As the name implies, variable means changed, it means that value stored in a variable can be changed until the end of runtime (PHP finishing executing all scripts), this is the main characteristic of variable, now let’s take a look deeper.
I. Declaring Variable In PHP
Some rules when declaring a variable:
- A variable must be started with a dollar sign ($) and followed by a variable name. Variable name must begin with a letter (a-z, A-Z) or underscore (_), then followed by letters (a-z, A-Z), numbers (0-9), or underscores (_).
- Variable name is case sensitive which means distinguishing between uppercase and lowercase, eg:
$user
is different from$User
. - We can’t name a variable with
$this
, because$this
is a special variable used by PHP to reference current class; - There are several predefined variables that used by PHP for certain purposes, such as
$ _POST
,$ _GET
,$ _COOKIE
,$ _SESSION
, and$ _SERVER
, these variables usually start with an underscore and use capital letters, so be careful with it because we can override it by accident.
Some examples of declaring variables:
<?php
// Valid
$user = 'John';
$_user = 'John';
$_user_name = 'John';
$_1 = 'John';
// Not Valid
$user-name = 'John'; // using dash
$1user = 'John'; // using number for first letter
II. Writing Tips and Writing Standards for Variable In PHP
In general programming, there are common writing standards that recommended to be followed so that our code will be easy to read and learn both by ourselves or other programmers who read our code.
There are 3 common methods for writing variables:
- Using Pascal Case, which every word begins with a capital letter, e.g.
$FirstName
,$CustomerFirstName
- Using Camel Case, the initial word begins with a lowercase and the rest begins with a capital letter, e.g.
$firstName
,$customerFirstName
- Using underscore, each word separated by underscore, e.g.
$first_name
,$customer_first_name
Every vendor (in CMS or Framework) use their own standard, I personally prefer using underscore because it is more clear and eye catching especially for variables with a long name.
In addition, when choosing a variable name, we should consider some matters:
- A variable name should reflect its contents, e.g.
$customer_email
for store customer email data. This is because it will make easier for us to quickly know the content of the variable especially when our code becomes more complex. - Use a unique prefix for variables that intended for a particular purpose e.g.: for config, use
cfg_
prefix, for example:$cfg_host
,$cfg_user
,$cfg_pass
this is to make the variable safe (not easily overwritten). - In a large scope, avoid using common variable names, such as
$val
or$value
, because it will be confusing. In addition, we can easily override it by accident, but for small scope, it’s ok to use it, for example for small scope of loop (foreach, for)
III. Storing Values
We use equal sign ( = ) to assign a value to a variable. We can assign all kind of data type into a variable, such as integer, string, float, boolean, array, object, etc, for example:
$value = true; // boelan
$name = 'John'; // String
$value = 10.5; // float
$array = array(); //array
$object = new Operate(); // Object
When storing a value, first, PHP will process the code located on the right side of the equal sign ( = ), then the result will be saved to the variable (the left side of the equal sign). By understanding this, our coding becomes more fast and effective.
An example:
$price = 10;
$price = $price + 5;
echo $price; // 15;
In the example above, first, PHP will execute statement of $value + 5
then the result will be assigned to the $price
variable, so now the $price
variable has a value of 15.
This is usefeul when we perfom a loop operation:
$values = array (5, 4, 7, 6, 10);
$total = 0;
foreach ($values as $val)
{
$total = $total + $val;
}
echo $total; //32
In the above code, the $total
variable overridden multiple times with a new value form the $val
variable.
Tips: From that behavior, we can learn that in a general case, sometimes we found that the value of variables don’t meet our expectation (the value changed), then for sure that the variable has been overwritten.
IV. Variable Scope
In PHP, we can access and use variables only in a certain area, this is called scope. The scope of variable is divided into two that are:
- Global scope. Variables are declared outside a function so that it can be accessed anywhere except inside a function.
- Local scope, Variables are declared inside a function, so it can only be accessed from that function.
$email = 'old_email@gmail.com'; // global scope
function print_email() {
$email = 'new_email@gmail.com';
echo $email;
}
$name = 'John';
function print_name() {
echo $name;
}
print_email(); // new_mail@gmail.com
echo $email; // old_email@gmail.com
print_name(); // error
The above example shows that the $email
variable that declared outside the function is not overridden even though we declare the same variable name inside the function.
In Addition, the print_name()
function will give a warning message tell us that the $name
variable is not declared, this is because we can’t access the $name
variable -which in global scope- from the function.
Example #2:
<?php
$email = 'email@gmail.com';
function print_email()
{
global $email;
echo $email;
}
print_email(); // email@gmail.com
?>
The above example shows that we can access global variables inside a function by using the global
keyword.
global
keyword, because in a complex code, e.g. for hundreds or thousands lines of code, we can accidentally change/override that variable.V. Variable Variables
Variable variables is a variable that formed from the value of another variable, for example:
<?php
$username = 'john';
$column_name = 'username';
echo $$column_name; // john
From the above example, the value of $column_name
is username, so that the $$column_name
equals to $username
.
This type of variables useful when we want to create dynamic variable names, such as when processing HTML form from user inputs, for example:
Form HTML that contains input field for name and email:
<?php
echo '
<form method="post" action="proccess.php">';
$inputs = array("name" => "Name", "email" => "Email");
foreach ($inputs as $input_name => $display_text)
{
echo '<label>' . $display_text . '</label>: <input name="' . $input_name . '" type="text" />';
}
echo '<input type="submit" name="submit" value="Submit" />
</form>';
?>
For example, we fill the form with the data: Name: john, Email: john@gmail.com. When we submit the form, the data will be sent to the proccess.php file. our proccess.php file contains the following code:
<?php
$list = array("name" => "Nama", "email" => "Email");
foreach ($inputs as $input_name => $display_text)
{
$$input_name = $_POST[$input_name];
}
echo $name; // john
echo $email; // john@gmail.com
?>
The above code shows that the $name
and $email
variables have same value as the form data.
More…
In this article, we have learned variable in php, for more references, you refer to its official page at: http://php.net/manual/en/language.variables.php
'[ 기타 활동 ] > PHP 7' 카테고리의 다른 글
How to Calculate Date and Time Difference in PHP – The Easiest Way (0) | 2018.07.21 |
---|---|
Understanding Time, Mktime, and Strtotime Function in PHP (0) | 2018.07.21 |
Understanding Constant in PHP – Updated to PHP 7 (0) | 2018.07.21 |
Retrieve Data From MySQL Database Using PHP (0) | 2018.07.21 |
15+ Most Used PHP Array Functions You Need to Know (0) | 2018.07.21 |