0v1.ro

(zero V unu)

Variables

Variables are preceded in PHP by a dollar sign $ and the rules for naming are: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*   or in plain english names of variables can begin with letters or underscores and then you can put other numbers letters and underscores. Letters here can include extended ascii characters from 7F to FF (127 – 255) so don’t blame me if you find letters like ç, † or ½

When declaring a variable, in PHP you don’t need to specify a type, it’s enough to give it a name and assign it a value. $var = “string value”;

Variables are case sensitive and some variable names are reserved: $this ( used inside objects), $_SERVER, $GLOBALS, $_SESSION, $_COOKIE, $_POST, $_GET, $_REQUEST, $_ENV (global variables).

When variables are not assigned values they behave as in the table above, but an E_NOTICE error is issued, and it is not recomanded to not properly initialize them or check if they are set with isset() function.

Situation Value
 NULL
 false
 abc   ( ” concatenated with ‘abc’ )
 25  ( 0+25 )
 1.25  ( 0+ 1.25)
 array(1) {  [3]=>  string(3) “def” }
adds empty array() with array with element key: 3, value “def”
 object(stdClass)#1 (1) {  [“foo”]=>  string(3) “bar” }
initializes an stdClass() object and assigns parameter foo the value ‘bar’

Variable variables

In PHP you even can have dynamic names for variables! You can create a variable using another variable value as it’s name

Variable variables can be defined as above or if you want to use an array key as name, you have to use curly brackets to avoid the ambiguity

It works with object properties too

If this is not too much already, try looking at the Example #1 in the PHP manual

Variable scope

Variable scope refers to the availability of variables in different contexts.

Inside functions you can access global variables using the keyword global

Global variables can be accessed using special PHP predefined variable $GLOBALS

Some of the predefined PHP variables are superglobals and can be accessed anywhere without the global keyword: $GLOBALS, $_SERVER, $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV;