<!DOCTYPE html> <html> <body> <?php $hlo = "Hello PHP coders!"; $a = 10; $b = 20.5; echo $hlo; echo "<br>"; echo $a; echo "<br>"; echo $b; ?> </body> </html>
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
<!DOCTYPE html> <html> <body> <?php $hello = "PHP Coders"; echo "Hello $hello!"; echo "<br/>"; $hello = "PHP Coders"; echo "Hello " . $hello . "!"; echo "<br/>"; $a = 5; $b = 4; echo $a + $b; ?> </body> </html>
The variables that are declared in a function are called local variables for that function, so outside of the function that variable is not used, it will show error - Undefined variable.
<!DOCTYPE html> <html> <body> <?php function loc_var() { $ab = 2; echo "Local variable 'ab' is : $ab"; } loc_var(); ?> </body> </html>
<!DOCTYPE html> <html> <body> <?php function loc_var() { $ab = 2; echo "Local variable 'ab' is : $ab"; } loc_var(); echo "Local variable out of function 'ab' is : $ab"; ?> </body> </html>
Output:
The global keyword is used to access a global variable from within a function
<!DOCTYPE html> <html> <body> <?php $var_name = "php coders point"; function glob_var() { global $var_name; echo "Variable in the function: ". $var_name; echo "</br>"; } glob_var(); echo "Variable outside of the function: ". $var_name; ?> </body> </html>
<!DOCTYPE html> <html> <body> <?php $var_name = "php coders point"; function glob_var() { echo "Variable in the function: ". $var_name; echo "</br>"; } glob_var(); echo "Variable outside of the function: ". $var_name; ?> </body> </html>
Output:
<!DOCTYPE html> <html> <body> <?php $number1 = 10; $number2 = 15; function glob_var() { $mul = $GLOBALS['number1'] * $GLOBALS['number2']; echo "Multiplication of global variables : " .$mul; } glob_var(); ?> </body> </html>
<!DOCTYPE html> <html> <body> <?php $number1 = 10; $number2 = 15; function glob_var() { $number1 = 10; $number2 = 10; $mul = $number1 * $number2."<br/>"; echo "Multiplication of global variables in a function : " .$mul."<br/>"; } glob_var(); $mul = $GLOBALS['number1'] * $GLOBALS['number2']; echo "Multiplication of global variables out of a function: " .$mul; ?> </body> </html>
Normally, when a function is executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.To do this, use the static keyword when you first declare the variable
<!DOCTYPE html> <html> <body> <?php function stati_var() { static $x = 3; echo $x; $x--; } stati_var(); echo "<br/>"; stati_var(); echo "<br/>"; stati_var(); echo "<br/>"; ?> </body> </html>
Note: The variable is still local to the function.