๐ PHP Variables & Constants: Your Data Storage Boxes
Imagine you have a magic house with different types of boxes to store your toys and treasures. Some boxes you can open and change whatโs inside. Others are locked forever with special treasures that never change. Thatโs exactly how PHP stores information!
๐ฆ What is a Variable?
A variable is like a labeled box where you put things. You can:
- Put something in the box
- Look at whatโs inside
- Replace it with something new
In PHP, every variable starts with a dollar sign $ โ think of it as a little price tag on your box!
$myToy = "Teddy Bear";
$age = 8;
$hasCandy = true;
Whatโs happening?
$myToyholds the word โTeddy Bearโ$ageholds the number 8$hasCandyholds true (yes!)
๐ท๏ธ Variable Naming Rules
Just like you canโt name your pet โ123Cat!โ (weird, right?), PHP has rules for naming boxes:
โ The Rules
| Rule | Good Example | Bad Example |
|---|---|---|
Start with $ |
$name |
name |
First character: letter or _ |
$_count |
$1count |
Only letters, numbers, _ |
$my_var2 |
$my-var |
| Case matters! | $Name โ $name |
โ |
// โ
GOOD names
$userName = "Alex";
$_secretCode = 1234;
$player1Score = 100;
// โ BAD names (will break!)
// $2fast = "error";
// $my-name = "nope";
// $hello world = "spaces!";
๐ฏ Pro Tip: Use Descriptive Names!
// Hard to understand
$x = 25;
// Easy to understand
$playerAge = 25;
๐ Variable Scope: Where Can Your Box Be Seen?
Imagine your house has different rooms. Some toys stay in your bedroom only. Others are in the living room where everyone can see them.
๐ Three Types of Scope
graph TD A[๐ PHP Scope Types] --> B[๐ Local<br/>Inside function only] A --> C[๐ Global<br/>Outside functions] A --> D[โก Static<br/>Remembers value]
1๏ธโฃ Local Scope โ Your Bedroom
Variables inside a function stay inside that function.
function sayHello() {
$greeting = "Hi!"; // Local
echo $greeting; // Works!
}
sayHello();
// echo $greeting; โ Error! Can't see it here
2๏ธโฃ Global Scope โ The Living Room
Variables outside functions need special permission to enter.
$familyName = "Smith"; // Global
function introduce() {
global $familyName; // Ask permission!
echo "We are the " . $familyName;
}
introduce(); // "We are the Smith"
3๏ธโฃ Static Scope โ The Memory Box
Normally, local variables forget everything after the function ends. Static variables remember!
function countVisits() {
static $count = 0; // Remembers!
$count++;
echo "Visit #" . $count;
}
countVisits(); // Visit #1
countVisits(); // Visit #2
countVisits(); // Visit #3
๐ฆธ Superglobals: The Superhero Boxes
These are special boxes that PHP creates for you. They work EVERYWHERE โ no permission needed! They always start with $_.
graph LR A[๐ฆธ Superglobals] --> B["$_GET<br/>URL data"] A --> C["$_POST<br/>Form data"] A --> D["$_SESSION<br/>User session"] A --> E["$_COOKIE<br/>Browser cookies"] A --> F["$_SERVER<br/>Server info"] A --> G["$_FILES<br/>Uploaded files"] A --> H["$_ENV<br/>Environment"] A --> I["$_REQUEST<br/>GET + POST"] A --> J["$GLOBALS<br/>All globals"]
๐ Quick Examples
// Getting data from a URL like:
// mysite.com?name=Alex
echo $_GET['name']; // "Alex"
// Getting form data
echo $_POST['email'];
// Server information
echo $_SERVER['HTTP_HOST']; // Your domain
// Session data (like a backpack)
$_SESSION['user'] = "Alex";
๐ Think of It Likeโฆ
| Superglobal | Real-Life Analogy |
|---|---|
$_GET |
A postcard with message visible |
$_POST |
A sealed letter (private) |
$_SESSION |
Your backpack for the day |
$_COOKIE |
A sticky note on your forehead |
$_SERVER |
Your ID card with all your info |
๐ Constants: The Treasure Chest
Unlike variables, constants NEVER change. Once you set them, theyโre locked forever โ like carving your name in stone!
๐ Two Ways to Create Constants
// Method 1: define()
define("SITE_NAME", "My Awesome Site");
define("MAX_PLAYERS", 100);
// Method 2: const (inside classes too!)
const PI = 3.14159;
const GAME_VERSION = "2.0";
โก Key Differences from Variables
| Feature | Variable | Constant |
|---|---|---|
| Symbol | $name |
NAME (no $) |
| Can change? | โ Yes | โ No |
| Case | $Name โ $name |
Usually UPPERCASE |
| Scope | Limited | Global everywhere |
define("GRAVITY", 9.8);
function calculateFall() {
// No 'global' needed!
return GRAVITY * 2; // Works directly!
}
โจ Magic Constants: The Shape-Shifters
These special constants change their value depending on where you use them! They have double underscores on both sides: __NAME__
graph LR A[โจ Magic Constants] --> B["__LINE__<br/>Current line number"] A --> C["__FILE__<br/>Full file path"] A --> D["__DIR__<br/>File directory"] A --> E["__FUNCTION__<br/>Function name"] A --> F["__CLASS__<br/>Class name"] A --> G["__METHOD__<br/>Class::method"] A --> H["__NAMESPACE__<br/>Namespace name"] A --> I["__TRAIT__<br/>Trait name"]
๐ฎ See Them in Action!
<?php
// In file: /var/www/app/game.php
echo __LINE__; // 5 (this line number)
echo __FILE__; // /var/www/app/game.php
echo __DIR__; // /var/www/app
function battle() {
echo __FUNCTION__; // "battle"
}
class Hero {
public function attack() {
echo __CLASS__; // "Hero"
echo __METHOD__; // "Hero::attack"
}
}
๐ฏ Why Are They Useful?
Perfect for debugging (finding problems):
function logError($message) {
echo "Error on line " . __LINE__;
echo " in file " . __FILE__;
echo ": " . $message;
}
๐ฎ Quick Summary: Your PHP Storage System
| Type | Symbol | Changes? | Where Works? |
|---|---|---|---|
| Variable | $name |
โ Yes | Depends on scope |
| Constant | NAME |
โ No | Everywhere |
| Superglobal | $_NAME |
โ Yes | Everywhere |
| Magic Constant | __NAME__ |
๐ Context | Everywhere |
๐ You Did It!
Now you understand how PHP stores data:
- Variables = Changeable labeled boxes
- Naming Rules = How to properly name your boxes
- Scope = Where your boxes can be seen
- Superglobals = Superhero boxes that work everywhere
- Constants = Locked treasure chests
- Magic Constants = Shape-shifting special values
Youโre ready to store and manage data like a PHP pro! ๐