PHP Variables
PHP Variables
Section titled “PHP Variables”Variables are fundamental building blocks in programming. Think of them as labeled containers or boxes where you can store information (data) that your script needs to work with.
This data can be text, numbers, or more complex structures.
Declaring (Creating) PHP Variables
Section titled “Declaring (Creating) PHP Variables”In PHP, variables are easy to create. They always start with a dollar sign ($), followed immediately by the variable’s name:
<?php// Assigning a string value$message = "Hello, PHP developers!";
// Assigning an integer value$userCount = 150;
// Assigning a floating-point (decimal) value$price = 99.95;
// Assigning a boolean value (true or false)$isLoggedIn = false;
// Assigning a null value (representing 'no value')$noValue = null;?>After executing this code:
$messageholds the text “Hello, PHP developers!”.$userCountholds the whole number 150.$priceholds the decimal number 99.95.$isLoggedInholds the boolean valuefalse.$noValueholds the special valuenull.
Key Points:
- PHP automatically determines the variable’s data type based on the value assigned.
- You don’t need a special command (like
intorstringin some other languages) to declare a variable before using it. A variable is created the moment you first assign a value to it using the assignment operator (=). - When assigning text (string) values, enclose them in single quotes (
'...') or double quotes ("..."). Double quotes allow variable interpolation (embedding variables directly inside the string), while single quotes do not.
PHP Variable Naming Rules
Section titled “PHP Variable Naming Rules”Variable names can be short (like $x, $i) or descriptive (like $customerName, $totalAmount). Descriptive names are generally preferred for better code readability.
Follow these rules when naming variables:
- Must start with the
$sign. - The first character after the
$must be a letter (a-z, A-Z) or an underscore (_). - Cannot start with a number immediately after the
$. ($1varis invalid). - After the first character, the name can contain letters, numbers, and underscores.
- Variable names are case-sensitive.
$nameand$Nameare two distinct variables.
| 💡 | Convention: While not enforced by PHP, the common convention (PSR standard) is to use camelCase for variable names (e.g., $firstName, $orderTotal). |
|---|
Outputting Variables
Section titled “Outputting Variables”The echo construct is commonly used to display data, including the values stored in variables, to the browser or console.
Outputting text and a variable:
<?php$websiteName = "CoolSite.com";echo "Welcome to $websiteName!"; // Variable interpolation within double quotes?>Using the concatenation operator (.):
<?php$websiteName = "CoolSite.com";echo 'Welcome to ' . $websiteName . '!'; // Concatenation works with single or double quotes?>Outputting the result of an operation:
<?php$quantity = 5;$unitPrice = 10.50;$totalCost = $quantity * $unitPrice;echo "Total cost: $" . $totalCost; // Outputs: Total cost: $52.5?>You’ll learn more about echo, print, and other ways to output data in later chapters.
PHP: A Dynamically Typed Language
Section titled “PHP: A Dynamically Typed Language”As seen in the examples, you don’t explicitly declare the data type (like integer, string, float) of a variable in PHP. PHP figures out the type dynamically at runtime based on the value assigned.
PHP automatically performs type juggling (implicit type conversion) when needed in operations. For example, adding an integer 5 to a string "10 apples" might result in the integer 15 (depending on the context and PHP version, with potential warnings).
While dynamic typing offers flexibility, modern PHP (version 7 onwards) also supports type declarations (scalar types, return types, property types) for function arguments, return values, and class properties. This allows for more robust and predictable code by enforcing types where desired, catching errors earlier.
This contrasts with statically typed languages (like Java, C#, C++) where you must declare the variable’s type before using it.
PHP Variable Scope
Section titled “PHP Variable Scope”The scope of a variable defines where in your script it can be accessed or modified.
PHP primarily has these variable scopes:
- Local: Variables declared inside a function are local to that function. They only exist and can only be accessed within that specific function.
- Global: Variables declared outside any function have global scope. They exist throughout the script but cannot be directly accessed inside functions by default.
- Static: A special type of local variable within a function that retains its value between function calls (unlike regular local variables which are destroyed when the function exits).
Global and Local Scope Examples
Section titled “Global and Local Scope Examples”A variable declared outside a function has GLOBAL SCOPE:
<?php$globalVar = 10; // Global scope
function testScope() { // Trying to access $globalVar directly here will cause an error or warning // echo "Inside function: " . $globalVar; // This would fail echo "Inside function: No direct access to globalVar.";}
testScope();
echo "<br>Outside function: " . $globalVar; // Accessing globalVar here is fine?>A variable declared within a function has LOCAL SCOPE:
<?phpfunction testLocalScope() { $localVar = 5; // Local scope echo "Inside function: localVar = " . $localVar;}
testLocalScope();
// Trying to access $localVar outside the function will cause an error// echo "<br>Outside function: localVar = " . $localVar; // This would fail?>| 💡 | You can have local variables with the same name in different functions without conflict, as each is confined to its own function’s scope. |
|---|
Accessing Global Variables: global Keyword and $GLOBALS Array
Section titled “Accessing Global Variables: global Keyword and $GLOBALS Array”If you need to access or modify a global variable from within a function, you have two main options:
- Use the
globalkeyword inside the function before the variable name. This tells PHP that the variable refers to the one in the global scope.
<?php$count = 0; // Global variable
function incrementCount() { global $count; // Declare intention to use the global $count $count++;}
incrementCount();incrementCount();
echo "Count is: " . $count; // Outputs: Count is: 2?>- Use the special
$GLOBALSsuperglobal array. PHP stores all global variables in this array, indexed by the variable name. You can access and modify globals directly through this array.
<?php$x = 5;$y = 10;
function addGlobals() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];}
addGlobals();echo $y; // outputs 15?>Best Practice: Over-reliance on global variables can make code harder to understand and maintain. It’s often better to pass needed values into functions as arguments and return results.
The static Keyword
Section titled “The static Keyword”Normally, when a function finishes executing, all its local variables are destroyed. If you call the function again, they are recreated from scratch.
Sometimes, you want a local variable to remember its value from the last time the function was called. Use the static keyword when declaring the variable the first time to achieve this.
<?phpfunction staticCounter() { static $counter = 0; // Initialized only the first time $counter++; echo "Counter is now: $counter<br>";}
staticCounter(); // Outputs: Counter is now: 1staticCounter(); // Outputs: Counter is now: 2staticCounter(); // Outputs: Counter is now: 3?>Each subsequent call to staticCounter uses the value $counter had at the end of the previous call. The static $counter = 0; line is effectively skipped after the first execution.
Note: The variable remains local to the function; it cannot be accessed from outside.