Define Variable in PHP
In this article, we will see about define variable in php.
PHP Variables
A Variable is a named memory location, whose value may change during the execution of a program.
Constant:
It is a named memory location, whose value never changes during the execution of a program.
I.e constant stays constant whereas variables vary.
While building any web application (ex. banking, game, etc.). we come across a variety of data and data values. According to the requirement of the application, we should be able to store and process them. To store and process data and data values we should be able to grab computer memory locations and access them within a script.
To grab a chunk of memory and access it within the script, we need to declare a variable or a constant. Declaring a variable or a constant means allocating a memory location for some data.
Initializing a variable or a constant: means putting an initial data value within that allocated memory location.
In order to change the value of a variable or constant, we need to assign a new value to it.
Assigning a variable or a constant: means putting a new data value within that allocated memory location.
Syntax:
// declaration and initialization of a variable
$variablename = initial value;
//assigning new value to a variable
$variablename = new value;
Example:
<?php
$player = "Ronaldo"; //declare and initializ variable
echo $player, "<br/>"; //access variable
$score = 4; //declaration and initialization of a variable
echo $score; //accessing variable
?>
/*
output:
Ronaldo
4
*/
Note :
- Variables and constants must be initialized when they are declared or defined.
- No comma-separated variables or constants are allowed, like in other languages.
- While accessing a variable directly within a string, it’s recommended to enclose a variable within{}