Variables and Constants

Loading concept...

๐Ÿ  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?

  • $myToy holds the word โ€œTeddy Bearโ€
  • $age holds the number 8
  • $hasCandy holds 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! ๐ŸŽ‰

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.