Variables & Scope
In PHP, all variables are declared with a leading dollar sign ($). PHP is dynamically typed, meaning you do not need to declare types before creating variables.
1 Dollar Prefix & Global/Static scopes
PHP scope rules differ from block-scope systems:
- Dollar Prefix (`$val`): All variables start with `$`. Names are case-sensitive (`$age` and `$AGE` are different).
- Global Keyword: Local functions cannot read variables declared outside their scope unless they explicitly declare them as global: `global $variable;`.
- Static Variables: Prefixing a variable with `static` inside a function preserves its value across multiple function calls.
- Constants: Created using the `define()` function or `const` keyword. They do not start with a `$` sign.
2 Variables Code
Let's run a program declaring variables and testing constants:
PHP — Variables
▶ Run Code
<?php
$name = "Balaji";
$age = 22;
// Define a constant
define("SITE_URL", "https://ourcompiler.com");
echo "Name: " . $name . "\n"; // '.' is used for string concatenation
echo "Age: " . $age . "\n";
echo "Constant URL: " . SITE_URL . "\n";
?>
3 Code Challenge
Challenge: Write a function containing a `static` variable counter. Increment it and invoke the function three times, printing the result to verify the counter variable's state is preserved.