What are Variables?
Variables are a fundamental building block of all programming languages. A variable is simply a placeholder for a value that you don’t know or that might change. The name of the variable remains the same but its value can change.
- In PHP variable always begin with a $ sign.
- Any combination of letters, number or underscore are valid.
- The first character after $ sign must not be a number.
- No spaces or hyphens are allowed.
- Names are case-sensitive.
Good Naming Practice
- Choose meaningful names.
- Don’t use short letters, except for counters.
- A good variable name makes your code easy to understand and maintain.
- Use camelcase or underscore for multiple words. Ex: $firstName, $first_name
- Make sure variables are case sensitive so $firstname is not same as $firstName.
$this -> is reserved variable for PHP object-oriented script. Check the list of all reserved variables here and avoid using them.
$firstName = 'KRITIKA'; $number = 24;
This value of a variable can come from:
- User input from an online form.
- From a database
- From PHP file itself.
$firstName = 'KRITIKA';
$number = 24;
- We assign the value to a variable by the assignment operator, which is simply an equal sign.
- The $firstname in the example above is a text and text is always written in quotes and after quotes, we put a semicolon. In computing terminology text is referred to as a string. So datatype of a variable is a string in above example. In PHP you do not need to specify a type of data stored by a variable in PHP.
- Another variable is $number. Numbers are not in quotes and can be in decimal.
- We have two variables in our code try to load them in a browser.
Difference between Print and echo
echo and print are basic ways to get output.
There is not much difference between echo and print.
|echo has no return value||print has a return value of 1|
|echo can take multiple parameters||print can take one argument|
echo "This ", "is ", "a ", "string ", "made ", "with multiple parameters.";
This is a string made with multiple parameters.
print "This ", "is ", "a ", "string", "made ", "with multiple parameters.";
FATAL ERROR syntax error, unexpected ‘,’ on line number 2