A PHP variable is a named container that holds data such as text, numbers, arrays, or objects in memory. Every PHP variable starts with a dollar sign $ followed by an identifier name, and PHP assigns its type dynamically when you store a value.
Follow these four rules whenever you name a variable in PHP:
$userAge and $_cacheKey are valid, whereas $2ndPlace causes a syntax error.$user-name.$orderId and $orderid are distinct.$this: $this is reserved inside classes to point to the active object instance.<?php
declare(strict_types=1);
$customerName = "Nadia Karim";
$itemCount = 3;
$unitPrice = 14.50;
$totalCost = $itemCount * $unitPrice;
echo "{$customerName} ordered {$itemCount} items for $" . number_format($totalCost, 2) . PHP_EOL;
Where you declare a variable controls which parts of your script can read or change it. Variables created inside a function stay local to that function and disappear once it finishes.
<?php
$siteCurrency = "USD"; // Global scope
function formatAmount(float $price): string
{
global $siteCurrency; // Pull global variable into function scope
static $callCount = 0; // Preserved across function calls
$callCount++;
return "[#{$callCount}] {$siteCurrency} " . number_format($price, 2);
}
echo formatAmount(25.0) . PHP_EOL;
echo formatAmount(40.5) . PHP_EOL;
Passing values into functions as parameters is much cleaner than relying on the global keyword, because it keeps dependencies explicit and easy to test.
$discount before assigning it triggers a warning in PHP 8 and defaults to null.global: Mutating global variables inside functions creates hidden side effects that make debugging painful.if: Writing if ($isAdmin = true) assigns true instead of checking equality with ===.No. PHP infers the type from the assigned value automatically, though you can enforce strict types on function parameters, return values, and class properties.
Use isset($var) to confirm a variable is declared and non-null, or use the null coalescing operator $name = $input ?? 'Guest'.
static variable inside a function do?A static local variable keeps its value between multiple calls to that same function instead of resetting on every call.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.