PHP
Variables
As with algebra, PHP variables are
used to hold values or expressions.
A variable can have a short name,
like x, or a more descriptive name, like carName.
Rules for PHP variable names:
- Variables in PHP starts with a $ sign, followed by the
name of the variable
- The variable name must begin with a letter or the
underscore character
- A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
- A variable name should not contain spaces
- Variable names are case sensitive (y and Y are two
different variables)
Creating
(Declaring) PHP Variables
PHP has no command for declaring a
variable.
A variable is created the moment you
first assign a value to it:
$myCar="Volvo";
After the execution of the statement
above, the variable myCar will hold the value Volvo.
Tip: If you want to create a variable without assigning it a
value, then you assign it the value of null.
Let's create a variable containing a
string, and a variable containing a number:
<?php
$txt="Hello World!";
$x=16;
?>
$txt="Hello World!";
$x=16;
?>
Note: When you assign a text value to a variable, put quotes
around the value.
PHP
is a Loosely Typed Language
In PHP, a variable does not need to
be declared before adding a value to it.
In the example above, notice that we
did not have to tell PHP which data type the variable is.
PHP automatically converts the
variable to the correct data type, depending on its value.
In a strongly typed programming
language, you have to declare (define) the type and name of the variable before
using it.