1. Variables in PHP
A variable in PHP is a named memory container for storing data values. In PHP, variables always begin with the dollar sign ($) followed by the variable name.
Variable Naming Rules:
- A variable name must start with a letter or an underscore (
_). - It cannot start with a number (e.g.,
$1itemis invalid). - It can only contain alphanumeric characters and underscores (
A-z,0-9, and_). - Variable names are case-sensitive (
$ageand$Ageare distinct).
2. PHP Data Types
PHP is a dynamically typed language (it automatically determines the type based on the assigned value). PHP data types are divided into three major categories:
A. Scalar Types
- Integer: Non-decimal numbers between -2,147,483,648 and 2,147,483,647 (32-bit systems) or larger (64-bit systems). Example:
$score = 98; - Float (Double): Numbers with decimal points or exponential forms. Example:
$rating = 4.85; - String: Sequences of characters. Example:
$name = "Rahul Sharma"; - Boolean: Represents truth values:
trueorfalse.
B. Compound Types
- Array: A collection of multiple values under a single name. Example:
$skills = ["PHP", "MySQL", "JavaScript"]; - Object: An instance of a programmer-defined class containing properties and methods.
C. Special Types
- NULL: A variable with no assigned value or explicitly set to
null. - Resource: Special handler referencing external resources (such as an open file stream or database connection).
3. Variable Scope
Scope refers to the context within which a variable is accessible:
- Local Scope: Variables declared within a function can only be accessed within that function.
- Global Scope: Variables declared outside any function have global scope and can be accessed anywhere outside functions. To access them inside a function, use the
globalkeyword or$GLOBALSarray. - Static Scope: When a function executes, its local variables are normally deleted. Declaring a variable as
staticpreserves its value across multiple function calls.
";
}
function countVisits() {
static $visitCount = 0; // Preserves value
$visitCount++;
echo "Visit count: " . $visitCount . "
";
}
countVisits(); // 1
countVisits(); // 2
countVisits(); // 3