Learn one of the most powerful programming languages in the world and become a rockstar developer.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for PHP variables:
$
sign, followed by the name of the variable$age
and $AGE
are two different variables)PHP has a total of eight data types which we use to construct our variables −
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php $x = 5; // global scope function adzetech() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } adzetech(); echo "<p>Variable x outside function is: $x</p>"; ?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php function adzetech() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } adzetech(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?>
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 adzetech(){ static $x = 0; echo $x; $x++; } adzetech(); adzetech(); adzetech(); ?>