PHP – Variables and Data Types
Variables are containers for storing data
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case sensitive ($y and $Y are two different variables)
Example:
<?php $txt="Hello world!"; $x=5; $y=10.5; ?>
Local and Global
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
global – Keyword
The global keyword is used to access a global variable from within a function.
<?php $x=5; $y=10; function myTest() { global $x,$y; // It takes the global variables x and y $y=$x+$y; } myTest(); echo $y; // Outputs 15 ?>
static – Keyword
Normally, when a function is completed/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:
<?php function myTest() { static $x=0; // the variable is static and it will not be deleted echo $x; $x++; } myTest(); // output is 0 echo "<br>"; myTest(); // output is 1 echo "<br>"; myTest(); // output is 2 echo "<br>"; myTest(); // output is 3 echo "<br>"; myTest(); // output is 4 ?>
The result is:
0
1
2
3
4
Data Types
The types of data the variables can content.
<?php // STRINGS // ------------------- $x = "Hello world!"; echo $x; echo "<br>"; $x = 'Hello world!'; echo $x; // INTEGERS // ------------------- $x = 5985; var_dump($x); // var_dump() function returns the data type and value of variables echo "<br>"; $x = -345; // negative number var_dump($x); echo "<br>"; $x = 0x8C; // hexadecimal number var_dump($x); echo "<br>"; $x = 047; // octal number var_dump($x); // FLOATING NUMBERS // ------------------- $x = 10.365; var_dump($x); // var_dump() function returns the data type and value of variables echo "<br>"; $x = 2.4e3; var_dump($x); echo "<br>"; $x = 8E-5; var_dump($x); // BOOLEANS // ------------------- $x=true; $y=false; // NULL // ------------------- $x="Hello world!"; $x=null; var_dump($x); ?>