PHP Variables Naming Rules
PHP Variables
Variables are used to store data numbers, text like string. the variable in PHP can change according to the script PHP Variables Naming Rules. But some important information to you know about variables:
PHP variable does not need to declare before the addition of value to it.
PHP automatically converts the variable to its correct data type according to value.
In PHP assignment operator (=) used to assign value to a variable.
Every variable in PHP Start with a dollar ($) symbol
PHP is a loose type of language
Variable declare as: $var_name=value.
When variable contain a string:
<?PHP
$txt= “Hello”;
$x=20;
?>
Naming Rules of PHP Variables
Variable start with letter or underscore”_”
Variable name only contains an alphanumeric character or underscore”_”(A to Z 0,9)
Space in the variable name not allowed
PHP names are case sensitive
If variable name more than one word in this situation it should be separate underscore”_”
For Example:
<?PHP
Declare a variable in PHP
$txt=” Hello”;
$num=10;
// when display variable value
Echo$txt;
// Output: Hello
Echo$num; // Output 10
?>
PHP Variable Scope
PHP variable declared anywhere in the script
Three types of variable scope
1.local
Local scope can only access within function
2.Global
Global scope can only access outside the function
3.Static
Static keyword first declare the variable PHP Variables Naming Rules
Global Variable Example:
<?php
$x=5;
$y=6;
Function test(){
Global $x,$y;
$y=$x+$y;
}
Test();
Echo$y;
?>
The output is: 15
?>
local Variable Example:
<?php
Function text(){
Echo”<p>Inside fuction:</p>”;
?>
static Variable Example:
<?php
function myTest(){
static $x=0;
echo $x;
$x++;
}
myText();
myText();
myText();
?>